# JSFE flows architecture guide

This guide is for developers new to JSFE. It explains the ideas behind the engine, the building blocks a flow set is
made of, what the caller sees and hears, and how a conversation can feel free and natural while the transactions in it
stay exact and safe. It introduces concepts; the [flow author reference](copilot-reference.md) is the precise
specification, and the [README](../README.md) is the API reference.

The examples use a fictional utility company. Every name and number in them is invented.

## 1. The problem: two kinds of software in one conversation

A caller who phones a utility might say any of these in one call:

- "How much do I owe?"
- "I want to pay 80 dollars with my card ending in 4242."
- "Wait, make it 60."
- "When is it due, by the way?"
- "Actually, can I talk to a person?"

Two very different kinds of software have to serve that call.

**A conversational AI** understands people. It copes with any wording, any language, answers out of order, changes of
mind and questions in the middle of a task. But it guesses, and a guess is never acceptable when money moves.

**A transactional script** is exact. It verifies the caller, collects every required field, reads the amount back,
asks for a clear YES and charges the card once. But a classic script is rigid: one question at a time, one expected
answer, and anything else is "Sorry, I didn't understand."

JSFE joins the two. **The flow owns the transaction; the AI helps only with understanding language, and every AI
decision is a choice from a short closed list that the flow then checks.** The AI never writes a value into a
payment, never confirms a charge and never decides what the business does.

## 2. The big picture

```mermaid
flowchart LR
   U([Caller: voice, SMS, chat]) --> H[Host application]
   H -->|updateActivity| E[JSFE engine]
   E -->|aiCallback: closed questions| AI[(Models: classifier and LLM)]
   E -->|CALL-TOOL| T[(Business APIs)]
   E -->|reply text, session| H
   H -->|no flow serves the turn| G[Host AI answer: RAG, guru]
```

- **The host** is your application: it owns the channels (phone, text, web), credentials, storage, model
  configuration and turn order. It calls `engine.updateActivity(...)` once per caller message and saves the session the
  engine returns.
- **The engine** runs flows. It decides whether the message belongs to a flow in progress, starts a new flow, or hands
  the turn back to the host.
- **Models** are reached only through the host's `aiCallback`. The engine builds every question it asks a model, and
  decodes every answer, so a host never interprets a model's output itself.
- **Tools** are the only way a flow touches the outside world (charge a card, send a text, open a ticket).
- **The host's own AI** answers whatever no flow serves: a general question, small talk, a product question answered
  from documents.

## 3. Building blocks

### Flow sets and tools

A flow set is a JSON array of flow definitions (`tenant.flows`) with a matching JSON array of tool definitions
(`tenant.tools`). A host usually composes several sets: the **system** set every tenant shares (identity checks, field
collectors, retries, handoffs), optional product sets (for example a store integration), and the **tenant** set with
that business's own flows. Flows reference each other by id, so a tenant set reuses shared workers instead of copying
them.

### Steps

A flow is made of steps. Most authors need only a handful:

| Step | What it does |
| --- | --- |
| `SAY` | Queue text for the caller. |
| `SAY-GET` | Say the queued text and wait for the caller's answer. |
| `SET` | Compute a value (a JavaScript expression) into a variable. |
| `CASE` / `SWITCH` | Branch on a condition or a value. |
| `FLOW` | Run another flow: `call` (and come back), `replace` or `reboot` ([how they differ](#how-flows-run-other-flows)). |
| `CALL-TOOL` | Call a registered tool, with an `onFail` route. |
| `END` | Finish this flow and return to the one that called it. |
| `RETURN` | Finish every flow and hand a reply (or the turn) to the host. |
| `DISPATCH` | Finish every flow and send this message to intent detection, as if it were the first message. |

### The four authoring concepts

Steps are the machine code. Authors mostly write **declarations**, and JSFE generates the steps.

| Concept | You declare | JSFE gives you |
| --- | --- | --- |
| **Form** | the inputs a task needs | collection in any order, validation, corrections, resume after a detour |
| **Provider** | the facts a flow can answer and where they come from | answers to exactly the fact asked, behind an identity gate |
| **Performer** | an action: its effect, gate, tool, confirmation and outcomes | a guarded, confirmed, single execution |
| **Worker** | a few explicit steps | a small reusable task (a calculation, a lookup, a handoff) |

**Forms: any order, one question at a time.** A form lists its inputs once. The engine loops: find the first missing
input, ask it, store whatever the answer actually contained, repeat. Because of that loop, a caller who says
everything at once, answers a later question early, corrects an earlier answer, or comes back after a detour needs no
special code:

```json
{
  "declarationVersion": 2, "id": "pay-bill", "primary": true,
  "description": "The caller wants to pay their bill now. Not: a question about a past payment.",
  "form": {
    "inputs": [
      { "name": "account", "field": "account_number" },
      { "name": "amount", "profile": { "kind": "amount", "min": 1, "money": { "currency": "USD", "cardinals": true, "intent": "payment" } },
        "question": "How much would you like to pay?", "question_es": "¿Cuánto desea pagar?" },
      { "name": "card", "form": "collect-credit-card" }
    ]
  }
}
```

Forms nest: a payment form contains a card form, which contains card-number, expiration and security-code fields. An
answer may fill an input of any active form in the chain, so "use the card ending in 4242" is understood while the
payment is still asking for the amount.

**Providers: answer what was asked.** A provider declares a catalog of facts (balance, due date, last payment), each
with its source path, its wording and the identity gate that protects it. JSFE derives the rest from that one catalog:
the `asked` parameter intent detection fills, the words that recognize each fact in the middle of another task, and the
menu offered after an answer. "When is it due?" gets the due date, not a summary of the whole account.

**Performers: actions with guard rails.** A performer is a form plus a declared action:

```json
"performs": [{
  "action": "bill_payment", "effect": "charge", "subject": "form.data.account",
  "gate": { "flow": "verify-caller", "verified": ["cargo.verified"] },
  "flow": "payment-execute", "confirm": { "exact": true },
  "outcomes": { "ok": "resolved", "failed": "unresolved", "unknown": "unresolved" }
}]
```

From that, JSFE refuses to run the action without the gate, binds the confirmation to the exact request the caller
heard, invalidates it when any input changes, and never treats a timeout as success.

**An unknown result.** A timeout after the card may have been charged leaves the result unknown. The engine handles it
for every action: the action is claimed once, a result that is not one of the declared `outcomes` counts as unknown,
and an unknown charge or cancellation is held, never repeated (only a `send` may declare an explicit retry). Where the
payment API accepts an idempotency key, the flow passes one as a tool argument as well.

### Shared data and shared functions

A value several flows use (a catalog, a list of services, a set of phrases) is written once in the set's data entry and
referenced as `{"$data": "path.to.value"}`; expressions read it as `$data.name`. A function several flows use is
written once in the set's functions entry and called as `fn.name(...)`. One source means two flows can never drift
apart.

### How flows run other flows

A running conversation is a stack of flows. The flow on top is the one executing; the frames below it wait for it to
finish. A `FLOW` step has three call types, and each treats the stack differently. `DISPATCH` is the fourth way to
move, and it is not a call at all.

| | Stack | When the new flow ends | Use it for |
| --- | --- | --- | --- |
| `call` (the default) | adds a frame | the calling flow continues at its next step | a sub-task with a result: look up, verify, ask |
| `replace` | swaps the top frame | control goes to whatever the replaced flow would have returned to | moving on, or trying the same flow again |
| `reboot` | clears the stack, then runs the flow | the conversation has no flow to return to | starting over from a dead end |
| `DISPATCH` step | clears the stack, then runs intent detection on the message | not applicable | a message that is not for this flow |

A failed answer that must be asked again needs no special support: the flow replaces itself and the frame is reused, so
it can repeat as often as its own limit allows.

**Restarting a flow from below it.** `replace` swaps only the top frame. If `verify-account` calls `ask-contact`, and
`ask-contact` replaces `verify-account` to start over, the original `verify-account` is still waiting underneath: one
more frame on every restart. For this, both sides opt in. The step sets `toParent: true` and the flow it restarts
declares `replaceTarget: true`. The `replace` then finds that waiting frame, drops everything above it and takes its
place, so the stack is the same height on every lap. With either side missing, or no such frame waiting, it is an
ordinary local `replace`, so a local restart of a marked flow is still available when it is what you want.

```json
{ "id": "verify-account", "replaceTarget": true, "steps": ["..."] }
{ "id": "start_over", "type": "FLOW", "value": "verify-account", "callType": "replace", "toParent": true }
```

**The trap: a direct call to something already running.** Forms are re-entrant: a form declares its inputs, and when one
is already filled it is skipped. So the safe way to reach another task, or to come back to this one, is `DISPATCH`. It
clears the stack, intent detection starts the right flow, and that flow resumes from its saved draft. Nothing piles up.

A direct `call` has none of that protection. It runs on top of whatever is open, so if the called flow can reach the
caller again, each lap adds frames until the engine refuses to go on (32 frames, with a warning naming the path past
24). The usual disguise is a callback: an input's `after` flow runs as a `call` after the input is accepted. Asking a
question in an `after` is fine. Starting a new request from one is not, and neither is a field being re-filled by the
reply to that question, so while an `after` runs, the fields of its form that carry an `after` cannot be filled from a
reply. A caller who changes the subject there leaves by `DISPATCH`.

So: `call` for a closed sub-task that finishes and comes back, `DISPATCH` for anything the caller asked for.

**The flow-trap check.** The validator reads the graph of who runs whom and reports each real trap once, as an error:

| Trap | What it is |
| --- | --- |
| `stack_growth` | a loop holding at least one `call`: every lap adds a frame |
| `spin` | a loop of `replace`s, or one closed by a `toParent` replace, with no question in reach: it never ends and never waits |

Not traps, so never reported: a flow replacing itself with a question in reach, `reboot` and `DISPATCH` (both clear the
stack), a `toParent` return to a `replaceTarget` flow with a question in reach, and a shared worker in the path (two
forms both using `run-form` are nesting, not a loop). A flow on a loop that a runtime limit ends declares it with
`loopBound: "3 mismatches, 2 resends"`; the check cannot read the guard, so a test must drive that loop to its limit.

Run it on compiled flows (`engine.flowsMenu`), because declared forms only become steps when compiled: on raw
declarations a question inside a form is invisible, and a good loop reads as a `spin`. It follows only fixed targets. A
target chosen at run time (`{{retry_flow}}`) and the loops inside a shared worker are not read, so those need journeys.
A host should refuse to deploy a set with a trap.

### Session state

The engine's session holds the flow stacks and `cargo`, the conversation's shared state. Form progress lives in
`cargo.forms`, so a task interrupted by a question, a detour or a different request resumes from where it was when the
caller comes back to it. The host stores the session between turns; the engine never stores anything itself.

### Deploying while conversations are in progress

A new flow set can go live while callers are in the middle of a flow. A flow's `version` decides what happens to them:

- **A minor or patch change** (`1.4.0` to `1.5.0`: new wording, a new fact, a fix) keeps the conversation going on the
  steps already saved in it.
- **A breaking change bumps the major** (`1.5.0` to `2.0.0`): an input, entry argument or shared name removed or
  renamed, or a value whose meaning changed. A conversation saved under the old major ends that task safely on its next
  turn, without running any action or reading the caller's message as an answer, and the caller is asked to state the
  request again.

`continuationBreaks(previousFlows, nextFlows)` compares a set with the deployed one and lists every removed name that
needs a major bump, so a forgotten bump fails the deploy instead of reaching a caller.

## 4. One turn, step by step

Every caller message travels the same path. The order is the design: **deterministic readers first, AI only where
language is genuinely ambiguous, and the host last.**

```mermaid
flowchart TD
   M[Caller message] --> A{Flow waiting for an answer?}
   A -->|yes| G{Whole answer *, EXIT, QUIT, SALIR, or keypad 9 on a call?}
   G -->|exit, not a declared choice| GX[End flows: global-exit answers]
   G -->|9, not a declared choice| GT[End flows: switch-to-text]
   G -->|no| R[Deterministic readers: keys, numbers, typed fields, exact phrases]
   R -->|read| V[Validate, store, ask next question]
   R -->|not read| K[Reply ranker: a closed choice]
   K -->|answers / a choice| V
   K -->|abort| X[End flows: request cancelled]
   K -->|new_request| D[DISPATCH]
   K -->|irrelevant| Q[Ask the question again; no flow moves]
   K -->|concern| C[Say what the process does and how to cancel; ask again]
   A -->|no| D
   D --> S1[Intent detection, stage 1: which primary flow, or None]
   S1 -->|a flow| S2[Stage 2: that flow's parameters]
   S2 --> F[Start the flow; its form validates every value]
   S1 -->|None| HA[Host answers with its own AI]
```

### Global keys: EXIT and keypad 9

Before any reader, a waiting question checks two whole answers that work everywhere (jsfe 1.42.0):

- **The global exit.** `*`, EXIT, QUIT or SALIR (repeated, or with please / por favor / now / ahora; CANCEL is not one) ends
  every flow, outcome `user_aborted`, reason `exit_requested`. The engine then starts `global-exit`: by default (1.52.0) it says the
  process was cancelled at the caller's request, or thanks a caller whose request was already resolved, and offers more help. A tenant
  gives the exit its own path with a flow that `wraps: "global-exit"`; a flow that declares its own exit destination (`cancel_flow`)
  keeps it. A set with neither a wrapper nor `global-exit` keeps the generic cancel reply.
- **Keypad 9 switches a call to text,** when the caller's number can take texts and the set has `switch-to-text`. Keypad 8
  (language) and 0 (a person) are the host's, before the engine.
- **A declared choice wins.** A question that offers its own choice for the word (its key or a phrase is `*`, EXIT, QUIT,
  SALIR, or 9) takes the answer, so a flow overrides a global key by declaring it. An amount question keeps a 9.

The reply ranker's `abort` is not the global exit: a model's reading of a withdrawal ends the flows with the generic cancel
reply.

### Deterministic readers

When a flow is waiting for an answer, the engine first tries to read it without any model: a keypad key, a phone number,
an email, an amount, a card number, a whole-answer phrase of a choice. The rules are strict on purpose:

- **The current question first.** An answer is read against the question being asked, and the inputs that question
  explicitly invites ("type NEW CARD, LINK, or a different amount" invites an amount).
- **Out of order needs the whole signature.** A number fills another field only when the whole number fits it: a
  fragment of a longer number fills nothing.
- **A confirmation is answered only when it is asked.** A stray "yes" never confirms anything that is not the current
  question.
- **One part of an answer never fills two fields.** Two fields of the same form that fit the same words are asked
  about, never ranked.

The engine records every out-of-order fill and every refused reading, so a host can log why a value was taken.

### The reply ranker

When the readers cannot read an answer that has words in it, the engine asks the **reply ranker** one question: what
does this reply do with the question the flow asked? The model picks from a closed list:

| Option | Meaning | What happens |
| --- | --- | --- |
| `answers` | the reply responds to the question | the flow continues; any value still goes through deterministic validation |
| `choice:<key>` | the reply picks one of the question's offered choices | that choice is the answer |
| `abort` | the caller withdraws the request | every flow ends; the caller hears that the request was cancelled |
| `new_request` | the caller clearly asks for something else | DISPATCH: the message goes to intent detection |
| `irrelevant` | the reply means nothing here: a stray word, an unfinished sentence, speech to someone else | the question is asked again; no flow moves |
| `concern` | the caller expresses doubt that the current process is what they need ("It's not a new address, I'm just changing the delivery address") | offered only when a form in the chain declares `user_description`: the caller hears it, how to cancel, and the question again; no attempt is counted |

**Saying what a process does.** A form declares `user_description` / `user_description_es` (the engine's own `{{...}}`
expressions, its inputs in scope, '' until answered); the nearest form in the chain that declares one is used. It is never offered at a reason question. A
top-scoring `concern` (cut 0.6) wins over a cleared choice.

**Options with arguments.** A declared choice may carry `parameters` (`{name,type,description}`): a pick then extracts them from the reply with the same stage as a flow's parameters, and the flow reads `{ key, arguments }`. The pick stands when extraction finds nothing or fails. The ranker is generic, so the flow supplies the context: a form's `confirm.reply_context` says what a reply may contain. The address read-back uses this: "It's Long Beach, apartment 4" changes the city and the apartment and reads the address back, with no further question.

### Arguments in free-form answers

A caller rarely answers in the shape a reader expects: "Voy a hacer un pago de 100 dólares", "I'd like to fly to
Cancún the week after Easter". The readers cannot read such a sentence, so it goes to the reply ranker. A flow can
declare the values to look for in it (jsfe 1.36, opt-in). The ranker then decides what the reply does, the parameter
stage (the same one that extracts a flow's arguments in intent detection) finds the values, and **the form's own
readers decide what each value is.** The model only finds the words; every reader rule and validator still applies.

**Where to declare them.** Each is a list of `{ name, description, type?, reads? }`:

| Declared on | Extracted when | Example |
| --- | --- | --- |
| an input: `rank_parameters` | the ranker says the reply `answers` the question | the amount question, the travel search question |
| a profile choice: `parameters` | the ranker picks that choice: the asked question's own, or another input's option offered with it | "different amount" carries the amount |
| a form's confirmation: `confirm.rank_parameters` | the ranker says the reply `answers` the confirmation | "No, make it 200 dollars" at "I'll charge $119.77…" |

**`reads` decides which question a value answers.** With `reads: '<input>'` the value is read as that input's
answer, wherever the question was: it can only become that input. Without `reads` it is read as the answer to the
question asked, exactly as if the caller had said only that value, so that question's rules decide where it goes (a
key, a sub account number, an invited amount). At a confirmation, a value without `reads` is read as a correction there.
Use `reads` for a value the caller clearly meant for one field; leave it out for a value whose field the question's
rules should decide.

**How the values are taken:**

- Each value is read by the readers as if said alone, then validated and stored like a typed answer, with the same
  acknowledgement, attempts and confirmation. A value read at a confirmation changes the form, which is confirmed again.
- Nothing read: the question is asked again, as without the declaration. Extraction failing behaves the same.
- Two readings of one input that differ take nothing: the question is asked again.
- A picked choice is applied first, then its arguments. An argument that answers the choice's own exclusive group
  replaces it, being the more specific answer ("other amount" with $100 is the amount $100).
- Each reading carries `origin: 'rank_argument'` and `argument: '<name>'`, so the input's validator can tell an
  extracted value from a typed one (a tenant's amount check treats an extracted definite amount as an amount, never a
  key or a sub account number).

**Writing the descriptions.** The description is the whole instruction to the model, so it states what counts and what
does not: "The amount the caller definitely wants to pay now … Empty when no number is meant as the amount to pay now:
an amount already paid, owed or asked about is not one." Ask for the value as the caller said it ("as the digits they
said, with cents only if they said cents"): the reader applies the rules, and a model that normalises a value can change
which rule applies. Use `type: 'string'` (the default) for anything a reader reads.

**Cost.** One extraction call, only on replies that already went to the ranker; a reply the readers read never reaches
it.

```js
{ name: 'selection', exclusive: true,
  rank_parameters: [
    { name: 'amount', reads: 'amount', description: 'The amount the caller definitely wants to pay now, …' },
    { name: 'amount_candidate', description: 'A number that may be the amount to pay now but could answer another option of this question, …' }],
  any_of: [ { name: 'option', profile: { kind: 'choice', choices: [ /* … */
      { key: 'amount', phrases: ['other amount', 'otro monto'], parameters: [{ name: 'amount', reads: 'amount', description: '…' }] } ] } },
    { name: 'amount', profile: { kind: 'amount', min: 0.01 } } ] }
```

**Word readers and the ranker.** An input with `profile.whole_phrases` reads a choice from words only when the whole reply is accounted for: its phrase, another input's argument, courtesy, connecting words and the input's `template_words`. A reply with any other word goes to the ranker, so a word inside a sentence ("Quiero hacer una nueva compra" at a pay menu) never picks an option. Compound answers that carry arguments stay with the reader ("pay $50 with my Visa card"), because a picked option extracts only the arguments it declares. A proposal's confirmation offers the ranker its input's choices, so a correction ("yes, it was stolen") picks the changed candidate.

**A number that must name itself.** `input.confirm_out_of_order: {word, word_es, message, message_es}` (default off): out of order a number fills this input only beside its word, in either language ("account 5373850"). Alone it may be something else, a code said with an extra digit, so nothing is filled: the caller hears `message` (`{value}` the number, digit by digit on a call; `{word}` the word) and the current question again, which counts as an attempt at that question. It works at `collect-input` and `confirm-form` questions. At its own question the number needs no word. A pattern field's `asked_regex` also reads out of order beside the word ("vencimiento 0 4 3 1"); a reading of the field asked now wins over a number refused for want of its word, and no line is said. The card presets declare it on the expiration (EXPIRATION / VENCIMIENTO), the security code (SECURITY CODE / CÓDIGO DE SEGURIDAD) and the billing ZIP (owner 2026-11-17). `collect-credit-card` also checks the completed card (`validate-credit-card`): a security code whose length is not its brand's (4 for American Express, 3 for others) is asked again. `authenticate-user`'s `code_confirm` takes the same declaration for a `code_validator`, whose flow reads it with the helpers `saysConfirmWord(answer, spec)` and `confirmOutOfOrderLine(spec, value, language, voice)`.

**An amount-shaped number is no ZIP.** `profile.refuse_amount_shape: true` (digits profile, default off): "119 19" (three digits then two) is not the field's digits out of order; at its own question it reads. Declared by the `zip` and `card_zip` presets; `card_zip` also takes a bare number out of order only beside ZIP / CÓDIGO POSTAL (`confirm_out_of_order`).

**A number of the wrong length says so.** A numeric field (`digits`, `phone` or `identifier` kind) that declares `digits` takes, at its own question, the one 3+ digit number of the wrong length that no other field read or refused; validation rejects it with the count heard and the count it takes (`length_message`), said with the question that re-asks. Routing is unchanged.

**A provider's menu.** `provides.menu.whole_phrases: true` (default off) applies the same rule to a menu: a fact's phrase answers only as the whole reply, and a phrase inside a longer sentence goes to the reply ranker, offered every fact with phrases, every action, `done` and a person. A fact pick is answered with every other fact that cleared `REPLY_ALSO_CUT` (0.6), so one sentence that asks two things hears both; an action pick runs alone. `answers` and `irrelevant` fall to the menu's plain DISPATCH, which hands the turn to the host without intent detection (a Guru answers from the user context the flow set); `new_request` runs intent detection. A reply with no phrase is unchanged. `menu.unanswered` handles a question the provider cannot answer: when a reply from its own menu comes back to it through intent detection with no fact to say, the caller hears the declared apology and offer (`provider-unanswered`) instead of the same facts again.

Some options are **never offered**, so the ranker cannot pick them: the YES of a firm confirmation (an input's, or a form's
confirmation of a payment), a `current_only` choice while another question is asked, and text. `exact` on a choice says how words
match it, not what it does, so exact choices are offered. A charge or a cancellation is bound by `confirm: {exact: true}`
on its action: it runs only on the values the caller confirmed (binding, not firmness). A form confirmation is firm only when it authorizes a payment (effect `charge`), unless the form declares
`confirm.confirmation`: a firm one offers the ranker NO, corrections and a person (a ranker can understand "no thanks,
maybe later" as NO; it can never produce a YES to a payment). Every other confirmation is soft: its YES is read as a
soft confirmation's and is offered to the ranker too. Options that cost more when wrong need a higher score (a NO that would cancel what the
caller was confirming, or a new request that leaves the question unanswered). A reply that clears no option is
`answers`, and the question is asked again if nothing usable was in it.

### DISPATCH

`DISPATCH` is the bridge back to free conversation. It ends the flows in progress and re-reads the message through
intent detection, in the same turn. If the message starts another flow, that flow starts; if not, the host answers it
with its own AI and the conversation context. Form progress is kept in `cargo.forms`, so when the caller returns to
the task ("OK, let's pay now"), the primary flow starts again and resumes from its saved draft instead of asking
everything again.

A flow can also ask a question whose answer is open ("Describe the problem") with a **contextual DISPATCH**
(`onResponse: "continue"`): the ranker decides whether the reply answers, withdraws, changes the subject or means nothing here, and an
answer's fields are extracted by the same parameter extraction intent detection uses.

**DISPATCH is not giving up.** Sending a caller to a person (the `give-up` worker) happens only after real attempts at
the answer ran out, or a service the flow needs failed. A caller who changed the subject is dispatched, never
transferred.

### Intent detection: two stages

With `engine.intentDetection = 'two-stage'` (the default is one single call):

1. **Which flow.** Only primary flows can start this way, and stage 1 reads only their `description`: what should
   start the flow and, in a `Not:` list, what belongs elsewhere. The answer is one flow or `None`.
2. **Which arguments.** For the chosen flow only, stage 2 extracts its parameters: closed values (an enum such as
   `asked: "balance"`, a boolean) and free text. A parameter the model cannot fill is left out, and the flow asks for
   it.

Each stage is one `aiCallback` call that carries instructions for both a classifier and an LLM, so a host can run
either, or race both. JSFE builds both sets of instructions and decodes both answers (`jsfe/host`), which keeps a
production host and a test harness on one implementation.

## 5. Why the transactions stay safe

The conversational freedom above never reaches the transaction directly. These are the guarantees, and where each one
lives:

| Guarantee | How |
| --- | --- |
| No private fact before identity is verified | a provider's `gate` and a performer's `gate` run the verification worker and check the verified paths |
| No value accepted unchecked | every value, whether read, extracted at activation or understood by the ranker, passes the same field validator |
| No charge without a clear YES | a form that charges (`effect: "charge"`, which requires `confirm: { exact: true }`) confirms firmly: only confirmation words or the option's exact phrases; never offered to the ranker |
| The YES confirms what the caller heard | consent is bound to the request and the input revision; changing any input invalidates it |
| "Yes, but make it 60" is not consent | an answer with YES plus a correction or another request is not approval of the old request |
| No guessed success | an executor reports success, failure or unknown; unknown holds the action, it is never retried as if it failed |
| One effect, once | effects run only through `CALL-TOOL`; the session records the attempt (`lastTurnToolCalls`) and the host never rolls such a turn back |
| No escape from a half-finished effect | `must_complete` keeps a payment's card questions in place: the ranker reads a worded reply, a pick is taken, a clear withdrawal ends the flows, and any other verdict stays, saying the form's `first_task` |

The host keeps its side of the contract: one `updateActivity` at a time per conversation; a cancelled turn is awaited,
not abandoned; a turn that attempted a tool is never restored to its earlier session; and external effects carry an
idempotency key where the backend supports one. The [README](../README.md) section "Host Responsibilities: Tool Calls,
Cancellation and Concurrency" explains each rule and the production incident behind it.

## 6. What the caller sees and hears

### Messages

- **`SAY` and `SAY-GET`** carry `value` and a per-language variant (`value_es`); the session's language picks one.
- **Voice and text differ.** A question may have written wording for text (`question_text`) and spoken wording for a
  call. On a call, offer keys ("press 1 or say YES"); in text, never say "press".
- **Spoken values.** Helpers read amounts, dates and last-four digits naturally on a call (`amountToSpeech`,
  `dateToWords`, `last4`).

### Questions and answers

- **Choices.** A choice has a key, phrases in each language and, on a call, keypad keys. A key matches only as the
  whole answer. Sensitive choices are `exact`.
- **Confirmations.** One attribute, `confirmation: "firm" | "soft"`, on all three confirmations: an input's, a form's
  `confirm`, and a proposal's policy. Declared, it is definite. Absent: firm only for a payment, soft otherwise (a
  proposal is soft). Firm: only confirmation words. Soft: the wider YES vocabulary, and the reply ranker may pick YES.
- **Proposals.** When the flow infers a value ("Is this the card ending in 4242?"), a proposal asks the caller to
  approve that one value. It never authorizes the final action.
- **Questions in the middle of a task.** "When is it due?" asked while paying is answered from the provider's catalog,
  and the payment asks its question again.
- **Menus after an answer.** A provider may offer a short menu ("To make a payment, say PAY. For a payment link, say
  LINK."). Menu choices start their flows; "no thanks" ends politely.
- **Misses.** An answer with words that the question cannot read goes to the reply ranker; one that picks nothing is
  asked again and counts against `max_attempts`. An answer without words (symbols, an unexpected key) is acknowledged
  and asked again three times, and the fourth goes to DISPATCH (`max_misses`, default 4). Validator rejections count
  against `max_attempts` (default 3), with a declared recovery (`on_exhausted`). Every question also accepts a request
  for a person.

### Endings

When the flows end, the turn closes in one of four ways, and each treats the caller's last message differently:

| Ending | The caller's last message | What the caller gets |
|---|---|---|
| **Completion**: the flow runs its last step, or reaches `END` | used by the flow | what the flow said this turn. If it said nothing on the turn it started, the engine's "Processing …" placeholder; on a later turn, "Flow completed." (`flow_completed_generic`). A flow says its result before it ends. |
| **`DISPATCH`** | passed on to intent detection, as if no flow had been active | the reply of the flow it starts, or, if none, the host's own answer. Anything the ending flow queued is not said. |
| **`RETURN` with a value** | kept by the flow: intent detection never sees it | the step's value. Queued text is not said unless the step sets `keepSay: true`. |
| **`RETURN ''`**: the fake flow | handed to the host, without intent detection running again | the host's own answer |

`RETURN` with a value is the one ending that keeps the message from intent detection and still tells the caller
something.

`RETURN ''` exists for the **fake flow**: a primary flow that deliberately does nothing, so that a message resembling
another flow's trigger is matched by it and answered by the host, instead of wrongly starting the similar flow. Its
description claims the message ("Not:" lines in the similar flow point here), and its only step is `RETURN ''`. A
`DISPATCH` cannot do this job: intent detection has just chosen this flow, so the engine refuses to route the same message
again. For the same reason a `DISPATCH` belongs only after a question.

So: completion for a finished task; `DISPATCH`, after a question, for a message that is not the flow's to handle;
`RETURN` with a value for a message the flow must answer but not pass on; a fake flow with `RETURN ''` for a message
that must not start a similar flow.

A flow ends with an outcome (`resolved`, `unresolved`, `deflected`, or `pending` for a task that was paused), and may
give the host recovery guidance (`resume`, `restart`, `hold`, `none`). Hosts use these for reporting and for what to
say when the conversation returns.

## 7. A conversation, annotated

```text
Caller: Hi, I want to pay my bill.
```
Intent detection, stage 1, picks `PayBill`; stage 2 finds no amount. The form's first missing input is the account.

```text
Agent:  To make a payment, I first need to verify your account. Please say or enter your account number.
Caller: 4417 2209
Agent:  I found the account. Please enter the 6-digit code I just sent to your phone ending in 12.
Caller: 381 552
```
Deterministic readers: the account number and the code are typed fields. The identity gate is now satisfied.

```text
Agent:  Your amount due is $84.20. How much would you like to pay?
Caller: When is it due, actually?
Agent:  Your payment is due on November 5. How much would you like to pay?
```
The question is a provider fact asked mid-form: answered, and the form asks its question again.

```text
Caller: Let's do 60 with the card ending in 4242.
```
One answer fills two fields: the amount (the current question) and the card (an input of the nested card form).

```text
Agent:  I'll charge $60.00 to the card ending in 4242. Press 1 or say YES to pay, or press 2 or say NO.
Caller: Yeah, but make it 70.
```
Not consent: YES plus a correction. The amount changes, the confirmation is invalidated, and the read-back is asked
again for $70.00.

```text
Agent:  I'll charge $70.00 to the card ending in 4242. Press 1 or say YES to pay, or press 2 or say NO.
Caller: Yes.
Agent:  Your payment of $70.00 was successful. Is there anything else I can help you with?
Caller: Do you have energy-saving rebates?
```
An exact YES to the current confirmation runs the charge once. The last question is not something this flow reads:
the ranker says `new_request`, DISPATCH sends it to intent detection, no flow serves it, and the host's own AI answers
it from the company's documents.

## 8. Design rules worth keeping

1. **Declare, don't script.** Write the manifest (inputs, facts, actions) first; let JSFE generate the steps.
2. **Support what the question invites, DISPATCH the rest.** Never build a natural-language interpreter for one field.
3. **One source for everything.** Shared workers, shared data, shared functions: copies drift.
4. **Flow behavior lives in flows.** Offers, prompts and wording belong to flow steps, not to the host. If a flow cannot
   express something, it is a feature request for the engine.
5. **Side effects only through `CALL-TOOL`,** with an `onFail` route and a declared answer for an unknown result.
6. **Sensitive decisions are bound.** Any action that charges, cancels or cannot be reversed declares
   `confirm: {exact: true}`: it runs only on the exact values the caller confirmed. How the YES is read is separate: a
   charge is asked as a firm confirmation, everything else softly, unless the form declares `confirm.confirmation`.
7. **Descriptions are for detection only.** A primary's description says what starts it and what does not; caller
   wording belongs in questions and fact renderers.
8. **`call` for a closed sub-task, `DISPATCH` for what the caller asked for.** A loop that grows the stack is a design
   bug, and the validator refuses it.
9. **Test journeys, not just units.** Run the real engine on the real set: in order, out of order, all at once,
   corrected, a mid-form question, a change of subject, a decline, voice and text, every language.

## Where to read next

- [Flow author reference](copilot-reference.md): every field, step, profile and rule, precisely.
- [README](../README.md): engine API, `aiCallback`, intent detection, the reply ranker and host responsibilities.
- [System flows](flows/system/README.md): the shared workers, a page and a chart per flow.
