The Flow Book
  1. Why Flow

One week at the support desk

  1. A payment that timed out
  2. What the run was told
  3. Writing the payments library
  4. Waiting for the manager
  5. The next morning
  6. When the process dies mid-call
  7. Fixing a bug in a half-finished run
  8. Three carriers at once
  9. Answering calls from your own service

Projects

  1. What people build
  2. A research agent you can check

The language tour

  1. Values, functions and blocks
  2. Records, choices and match
  3. Modules, libraries and Python functions
  4. Result, ToolProblem and ?

Appendix

  1. The flow command
Language reference ↗

Why Flow

This book is about a small language for one stretch of a program: the part that asks other systems for things and then has to live with the answers. A model writes a draft, a payment provider moves money, a person decides something tomorrow. That stretch is usually short, and it is where a surprising share of the bugs nobody can reproduce comes from.

You are on the support desk of a small shop, and before any Flow, here is one of those bugs, written in Python and small enough to run on your machine.

An email nobody approved

The desk answers complaints. A model drafts a reply, the manager approves it, and a mail service sends it. This is the version most of us would write first:

# Draft a reply to a complaint, ask the manager, send it.import sysfrom services import draft_reply, ask_manager, send_emailcustomer, email = sys.argv[1], sys.argv[2]draft = draft_reply(email)answer = ask_manager(f"Send this to {customer}?\n\n{draft}")if answer == "Approve":    print("sent", send_email(customer, draft))
Draft a reply, ask the manager, send it.

The manager doesn't sit at a prompt waiting for the script. ask_manager writes the question to question.txt, and if there is no answer yet, the script exits; something runs it again later. That something might be cron, a queue worker or you pressing a button. The shape is the same.

Show python/services.py · 30 lines
# Stand-ins for a model, a manager and a mail service. Nothing here leaves the# directory: each service appends what it was asked to calls.log.import os, sysDRAFTS = [    "Sorry, Dana. We have refunded the 40 dollars for order A-1042.",    "Dana, we're sorry about the lamp. A new one ships today, free of charge.",]def log(line):    with open("calls.log", "a") as f:        f.write(line + "\n")def draft_reply(email):    # A model rarely writes the same email twice; this one alternates.    asked = sum(1 for line in open("calls.log")) if os.path.exists("calls.log") else 0    log("draft_reply")    return DRAFTS[asked % 2]def ask_manager(question):    # The manager reads question.txt and writes an answer to answer.txt.    if os.path.exists("answer.txt"):        return open("answer.txt").read().strip()    open("question.txt", "w").write(question + "\n")    sys.exit("waiting for the manager")def send_email(to, body):    log("send_email")    open("outbox.txt", "a").write(f"to {to}: {body}\n")    return "msg-5512"
Stand-ins for the model, the manager and the mail service. Each records what it was asked in calls.log.

On Monday evening, Dana writes in: her desk lamp arrived broken. The script drafts a reply and puts it to the manager, who has already gone home:

python3 desk.py dana@example.com 'Order A-1042, the desk lamp, arrived broken.'waiting for the manager
cat question.txtSend this to dana@example.com? Sorry, Dana. We have refunded the 40 dollars for order A-1042.

On Tuesday morning the manager reads question.txt, agrees with it, and writes Approve into answer.txt. The script runs again:

Goes wrong
python3 desk.py dana@example.com 'Order A-1042, the desk lamp, arrived broken.'sent msg-5512
Goes wrong
cat outbox.txtto dana@example.com: Dana, we're sorry about the lamp. A new one ships today, free of charge.

The manager approved a refund. Dana was promised a free lamp.

No single line of desk.py is wrong. Tuesday's run started at the top, as programs do, and the top of this one is a call to the model. The model wrote a different email, as models do, and the manager's answer to Monday's question was applied to text the manager had never seen. The log shows the model being asked twice:

cat calls.logdraft_replydraft_replysend_email

Fixing it in Python

You can fix this, and if you have shipped code like it, you probably have. Save the draft next to the question, keyed by the order, and read it back on the second run. Then remember that the process can die after send_email returns and before anything records that it did, so check the outbox before you send. Then finance asks what the model actually wrote on Monday, so keep that as well.

Every one of those fixes is right. Put together, they are a small database of what the script was told, designed by hand for this one script, and each new step needs its own entry and its own "did we already do this?" check. Add a second approver or a refund call and you are designing the table again.

Teams get tired of writing that table, which is why durable execution engines exist. Temporal, the best known, records the result of each activity and replays the workflow's code against those results after a crash. Flow starts from the same idea. The difference is that Flow is a language built around it, and the last sections of this chapter say why that matters.

The same desk in Flow

Here is the program in Flow:

use "./tools"pub type Outcome { Sent(Text), Held }pub flow main(customer: Text, email: Text) -> Result<Outcome, ToolProblem> = {    let draft = tools.draft_reply(email)?    match tools.ask_manager("Send this to ${customer}?\n\n${draft}")? {        Approve => Ok(Sent(tools.send_email(customer, draft)?)),        Deny => Ok(Held),    }}
The desk again: draft, ask, send.

It reads like desk.py. Three differences are visible.

The three services come from a library, imported with use "./tools". In Flow, anything that reaches outside the program is a Tool: a function whose body lives outside Flow, written in Python or Rust, or served by an MCP server. A Tool library is a directory of ordinary code, here one Python file. flow build reads that code and writes the Flow declarations for it, so you never write a Tool's signature twice.

def answered(kind, question):    """The answer answers.json holds for this call's key, read as kind. Until it    holds one, write the question with the key to questions.txt and hold."""    key = str(context().key)
Show all 77 lines of tools/tools.py
# Stand-ins for a model, a manager and a mail service, as a Tool library.# The manager is a person: ask_manager writes the question to questions.txt and# holds its call until answer.py saves their answer and the run asks again.# Nothing leaves this directory: each service appends what it was asked to calls.log.import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom flow_toolkit import DecodeError, Hold, context, from_json, log, tool, variantDRAFTS = [    "Sorry, Dana. We have refunded the 40 dollars for order A-1042.",    "Dana, we're sorry about the lamp. A new one ships today, free of charge.",]CALLS = Path("calls.log")def log_call(line):    with CALLS.open("a") as calls:        calls.write(line + "\n")@variant@dataclass(frozen=True)class Approve:    pass@variant@dataclass(frozen=True)class Deny:    passAnswer = Approve | Denydef answered(kind, question):    """The answer answers.json holds for this call's key, read as kind. Until it    holds one, write the question with the key to questions.txt and hold."""    key = str(context().key)    questions = Path("questions.txt")    if key not in (questions.read_text() if questions.exists() else ""):        with questions.open("a") as file:            file.write(f"{key} {question}\n")    answers = Path("answers.json")    saved = json.loads(answers.read_text()) if answers.exists() else {}    if key not in saved:        raise Hold()    try:        return from_json(kind, saved[key])    except DecodeError as error:        log(f"{saved[key]} is not an answer: {error}")        raise Hold()@tooldef draft_reply(email: str) -> str:    """Draft a reply to a customer. Like a model, it rarely writes the same one twice."""    asked = len(CALLS.read_text().splitlines()) if CALLS.exists() else 0    log_call("draft_reply")    return DRAFTS[asked % 2]@tooldef ask_manager(question: str) -> Answer:    """Put a question to the manager. A person answers it, later."""    return answered(Answer, question)@tooldef send_email(to: str, body: str) -> str:    """Send an email and return the mail service's message id."""    log_call("send_email")    with Path("outbox.txt").open("a") as outbox:        outbox.write(f"to {to}: {body}\n")    return "msg-5512"
The model's stand-in again, now as a Tool: the decorator is the one change.
Show tools/contract/lib.flow · 16 lines
// Generated by flow build from python module tools. Do not edit.// from tools.py: Answerpub type Answer { Approve, Deny }/// Draft a reply to a customer. Like a model, it rarely writes the same one twice.// from tools.py: draft_replypub flow draft_reply(email: Text) -> Text/// Put a question to the manager. A person answers it, later.// from tools.py: ask_managerpub flow ask_manager(question: Text) -> Answer/// Send an email and return the mail service's message id.// from tools.py: send_emailpub flow send_email(to: Text, body: Text) -> Text
What flow build wrote from tools.py. You commit it and never edit it.

Every call ends in ?. A call to another system can fail without giving an answer, and Flow makes the program say what happens then: each call returns either the Tool's answer or a ToolProblem saying why there isn't one, such as the Tool never starting or stopping before it answered. A failure a Tool reports itself, like a declined card, belongs to its answer instead, and these three report none. Here ? hands any problem straight back as main's result. A payment that timed out does something more careful with it.

The match on the manager's answer has to cover both answers. Leave out Deny, and the program does not run:

flow check desk.flowFound 1 error error[non-exhaustive-match]   × this match does not cover `Deny`   ╭─[desk.flow:7:5] 7 │ ╭─▶     match tools.ask_manager("Send this to ${customer}?\n\n${draft}")? { 8 │ │           Approve => Ok(Sent(tools.send_email(customer, draft)?)), 9 │ ╰─▶     }   ╰────   Why  The subject has type Answer; `Deny` is a value shape not covered by an unguarded arm.   Help  Add an arm matching `Deny` with the intended result, or add a final catch-all arm. Guarded arms do  not establish exhaustiveness.

What the listing doesn't show is the part that fixes Tuesday. Every time the program calls a Tool, Flow writes the call down, and when the answer arrives, Flow writes that down too, before the program is allowed to use it. The program's input is in that record as well.

Monday

The manager is a person, and a person doesn't answer within a function call. So ask_manager doesn't try. It holds its call: it promises an answer later, and Flow keeps the call open until one arrives.

@tooldef ask_manager(question: str) -> Answer:    """Put a question to the manager. A person answers it, later."""    return answered(Answer, question)
Show all 77 lines of tools/tools.py
# Stand-ins for a model, a manager and a mail service, as a Tool library.# The manager is a person: ask_manager writes the question to questions.txt and# holds its call until answer.py saves their answer and the run asks again.# Nothing leaves this directory: each service appends what it was asked to calls.log.import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom flow_toolkit import DecodeError, Hold, context, from_json, log, tool, variantDRAFTS = [    "Sorry, Dana. We have refunded the 40 dollars for order A-1042.",    "Dana, we're sorry about the lamp. A new one ships today, free of charge.",]CALLS = Path("calls.log")def log_call(line):    with CALLS.open("a") as calls:        calls.write(line + "\n")@variant@dataclass(frozen=True)class Approve:    pass@variant@dataclass(frozen=True)class Deny:    passAnswer = Approve | Denydef answered(kind, question):    """The answer answers.json holds for this call's key, read as kind. Until it    holds one, write the question with the key to questions.txt and hold."""    key = str(context().key)    questions = Path("questions.txt")    if key not in (questions.read_text() if questions.exists() else ""):        with questions.open("a") as file:            file.write(f"{key} {question}\n")    answers = Path("answers.json")    saved = json.loads(answers.read_text()) if answers.exists() else {}    if key not in saved:        raise Hold()    try:        return from_json(kind, saved[key])    except DecodeError as error:        log(f"{saved[key]} is not an answer: {error}")        raise Hold()@tooldef draft_reply(email: str) -> str:    """Draft a reply to a customer. Like a model, it rarely writes the same one twice."""    asked = len(CALLS.read_text().splitlines()) if CALLS.exists() else 0    log_call("draft_reply")    return DRAFTS[asked % 2]@tooldef ask_manager(question: str) -> Answer:    """Put a question to the manager. A person answers it, later."""    return answered(Answer, question)@tooldef send_email(to: str, body: str) -> str:    """Send an email and return the mail service's message id."""    log_call("send_email")    with Path("outbox.txt").open("a") as outbox:        outbox.write(f"to {to}: {body}\n")    return "msg-5512"
The manager's Tool posts the question and holds the call.

answered, a few lines above it in tools.py, writes the question to tools/questions.txt with the call's key, the run's id and the call's id together, and holds the call until an answer is saved under that key.

Each KEY=VALUE gives one of main's parameters, and the run's record is kept under ~/.flow, Flow's home:

flow run desk.flow customer=dana@example.com email='Order A-1042, the desk lamp, arrived broken.'run 9a850c0ce4499a850c0ce449 waiting: every open call waits for a replyopen root#2, held by its implementation  key: 9a850c0ce4499a850c0ce4499a850c0c/root#2  tools.ask_manager    arguments: {"question":"Send this to dana@example.com?\n\nSorry, Dana. We have refunded the 40 dollars for order A-1042."}reply details: flow show 9a850c0ce449 'root#2'next: flow show 9a850c0ce449

The run asked the model for a draft, built the manager's question from it, and is waiting at that question, the second call it made (root#2). The question is posted, with its key:

cat tools/questions.txt9a850c0ce4499a850c0ce4499a850c0c/root#2 Send this to dana@example.com? Sorry, Dana. We have refunded the 40 dollars for order A-1042.

The model was asked once:

cat tools/calls.logdraft_reply

That evening you shut the laptop. The run does not need a process to get through the night, because everything it has been told is already on disk. The process that started it has exited, and the run is listed as waiting:

flow runs9a850c0ce449	waiting	desk.flow	…		1 call held

Tuesday

The manager approves. The answer goes back to the library that asked, saved under the question's key by the library's own small script:

# The person's side of questions.txt: python3 tools/answer.py KEY ANSWER saves# ANSWER, written as JSON, for the question KEY names. The Tool reads it when# the run asks that call again, with flow resume RUN --resend CALL.import jsonimport sysfrom pathlib import Pathkey, answer = sys.argv[1], sys.argv[2]answers = Path(__file__).with_name("answers.json")saved = json.loads(answers.read_text()) if answers.exists() else {}answers.write_text(json.dumps({**saved, key: answer}, indent=2) + "\n")
The manager's side: save an answer for a key.
python3 tools/answer.py '9a850c0ce4499a850c0ce4499a850c0c/root#2' '"Approve"'

Then you continue the run, and --resend asks the manager's call again, so the library can return the answer it now has:

flow resume 9a850c0ce449 --resend 'root#2'Ok(Sent("msg-5512"))note: Open calls were selected for resend. The original call ID does not guarantee external deduplication; an external effect may happen again.9a850c0ce449 completednext: flow replay 9a850c0ce449
cat tools/calls.logdraft_replysend_email
cat tools/outbox.txtto dana@example.com: Sorry, Dana. We have refunded the 40 dollars for order A-1042.

The model was asked once, and Dana got the email the manager read.

Tuesday's process ran main from the top, exactly as desk.py did. When it reached draft_reply, the record already held that call's answer, so Flow handed the program Monday's draft without asking the model. From that draft the program built the same question it built on Monday, so the manager's call was the one the manager had answered. --resend asked that call again, under the same key, and the library returned the saved answer. send_email was the only new call Tuesday's process made.

Since every answer the run received is on disk, the finished run can be checked against its record at any time, with no Tool reachable at all:

flow replay 9a850c0ce449Replay 9a850c0ce449: matchedNo tools were called.

Nothing in desk.flow saves state, checks whether a step already happened, or writes a log. The table you would have designed for desk.py is the record, and Flow keeps it for every program.

The rule underneath

All of that follows from one rule:

A Flow program reaches the outside world only through Tool calls, and Flow records everything the program could not have computed itself: its input and the answer to every call.

Three carriers at once adds one more kind of thing to that record, for programs that do several things at once: which of them finished first.

The rule has two halves, and Tuesday needed both. The record held Monday's draft. And because the program computes everything else from its input and the answers, Tuesday's process built the question from that draft exactly as Monday's had, so the manager's answer fitted it.

Why it has to be a language

Suppose desk.py put the time in the question, Send this to Dana? (drafted 18:02). Tuesday's run would build a different question from the same draft, and anything replaying the script against Monday's record could no longer tell whether the manager's answer belonged to it.

A Python library could record calls the way Flow does, and ask you to send every clock read, file read and environment lookup through it. It can ask; it cannot stop the dependency you did not write from reading the clock anyway. Temporal meets the same problem with a sandbox for Python workflows and a static checker for Go, and its documentation says that neither catches everything.

Flow has no clock to read outside a Tool call. The clock is a Tool library, and its answer goes into the record like the model's. There is no file read, network request or random number either, except through a Tool. So there is no stray read for a checker to find; the program has nowhere to make one.

What it costs

Flow is small and closed, and that has a price. Inside a run you can't reach for your usual language's libraries: no HTTP client, no ORM, no datetime. Anything like that is a Tool, written in Python or Rust and called from Flow. Flow is also young and pre-release. The formats in this book will change before version 1, few people know the language yet, and you build the CLI from source.

Flow also does less than you might expect. It doesn't run a service, schedule jobs or draw a dashboard of runs. Your application does those things: it starts runs, answers their calls and decides when to resume them. On Monday and Tuesday that application was you, typing commands. Flow handles what happens in between.

So Flow pays for itself where what happened matters as much as the result: money, messages, approvals, waits that last days, work you may have to explain to someone later. For a request handler that reads a row and returns it, it is overhead.

How this book works

Most chapters follow the same support desk through a bad week. Each one starts from something going wrong, like the timed-out payment or the process killed mid-refund, and builds the program that handles it. The chapters build on each other, so read them in order the first time.

Flow is introduced as the story needs it. If you would rather learn the whole language before using any of it, read the language tour first and come back.

A few conventions:

  • Listings name their file and keep its line numbers. Files you only need to skim are folded; open them if you want the details.
  • A red edge marks a listing or a session that shows a mistake on purpose, like Tuesday's run of desk.py above. Don't copy it.
  • Notes in the margin hold asides: history, comparisons with other tools, the occasional remark. Skip them if you like.
  • Each chapter ends with exercises. Most of them ask you to break a run and see what the record says.

To follow along you need a browser for the examples with a Run button, which run in the page, and for the rest, the Flow CLI built from source, Python 3.11 or newer with the Python toolkit that page installs, and the support-desk project, which holds every chapter's files. This chapter's are in 0-why-flow. Nothing in this book contacts a real model, payment provider or carrier. The services are stand-ins like the ones above, so you can see exactly what each run was told.

This book teaches the language; it does not define it. When you need an exact rule, the Reference has it.

Exercises

  1. Fix desk.py so Tuesday's run sends the draft the manager approved. Count the lines you add, and list every file the second run now has to read before it does anything.
  2. With your fix in place, make send_email raise an exception after it appends to outbox.txt, then run the script again. Did Dana get one email or two?
  3. Start Monday's Flow run again and give the manager's call '{"Ok":"Deny"}'. What does the run return, and what is in tools/calls.log?
  4. In desk.flow, change send_email's arguments to (customer, "${draft}\n\nThe Shop"). After Fixing a bug in a half-finished run you will be able to say what happens to a run that was waiting when you made that edit.