jsfe 1.7.8 → 1.7.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +2 -3
  2. package/dist/forms/authoring.d.ts +10 -0
  3. package/dist/forms/authoring.d.ts.map +1 -0
  4. package/dist/forms/authoring.js +110 -0
  5. package/dist/forms/choice-flow.d.ts +0 -4
  6. package/dist/forms/choice-flow.d.ts.map +1 -1
  7. package/dist/forms/choice-flow.js +10 -14
  8. package/dist/forms/continuation-safety.d.ts.map +1 -1
  9. package/dist/forms/continuation-safety.js +2 -1
  10. package/dist/forms/contracts.d.ts +8 -4
  11. package/dist/forms/contracts.d.ts.map +1 -1
  12. package/dist/forms/contracts.js +46 -23
  13. package/dist/forms/declaration-capture.d.ts +7 -0
  14. package/dist/forms/declaration-capture.d.ts.map +1 -0
  15. package/dist/forms/declaration-capture.js +15 -0
  16. package/dist/forms/declarations.d.ts +20 -0
  17. package/dist/forms/declarations.d.ts.map +1 -0
  18. package/dist/forms/declarations.js +272 -0
  19. package/dist/forms/flows.d.ts.map +1 -1
  20. package/dist/forms/flows.js +47 -50
  21. package/dist/forms/identity-flows.js +8 -8
  22. package/dist/forms/index.d.ts +4 -0
  23. package/dist/forms/index.js +5 -1
  24. package/dist/forms/inspection.d.ts +12 -0
  25. package/dist/forms/inspection.d.ts.map +1 -0
  26. package/dist/forms/inspection.js +120 -0
  27. package/dist/forms/prompt-compiler.d.ts.map +1 -1
  28. package/dist/forms/prompt-compiler.js +5 -1
  29. package/dist/helpers/answer.d.ts +1 -1
  30. package/dist/helpers/answer.js +2 -2
  31. package/dist/helpers/contextual-response.d.ts +3 -0
  32. package/dist/helpers/contextual-response.d.ts.map +1 -1
  33. package/dist/helpers/contextual-response.js +7 -0
  34. package/dist/helpers/form-sources.js +1 -1
  35. package/dist/helpers/form-state.d.ts +1 -1
  36. package/dist/helpers/form-state.d.ts.map +1 -1
  37. package/dist/helpers/form-state.js +7 -5
  38. package/dist/helpers/index.d.ts +6 -5
  39. package/dist/helpers/index.d.ts.map +1 -1
  40. package/dist/helpers/index.js +4 -4
  41. package/dist/helpers/match-inputs.d.ts.map +1 -1
  42. package/dist/helpers/match-inputs.js +12 -40
  43. package/dist/helpers/money.d.ts +5 -3
  44. package/dist/helpers/money.d.ts.map +1 -1
  45. package/dist/helpers/money.js +25 -10
  46. package/dist/helpers/named-functions.d.ts +5 -0
  47. package/dist/helpers/named-functions.d.ts.map +1 -0
  48. package/dist/helpers/named-functions.js +54 -0
  49. package/dist/helpers/proposal-contract.js +4 -4
  50. package/dist/host/capabilities.d.ts.map +1 -1
  51. package/dist/host/capabilities.js +11 -3
  52. package/dist/host/registry-composition.d.ts.map +1 -1
  53. package/dist/host/registry-composition.js +9 -3
  54. package/dist/index.d.ts +15 -11
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +80 -51
  57. package/dist/runtime-identity.js +1 -1
  58. package/docs/copilot-reference.md +336 -66
  59. package/docs/development-release.md +16 -1
  60. package/package.json +1 -2
  61. package/dist/helpers/semantic-input-prompt.d.ts +0 -2
  62. package/dist/helpers/semantic-input-prompt.d.ts.map +0 -1
  63. package/dist/helpers/semantic-input-prompt.js +0 -153
  64. package/dist/helpers/semantic-input.d.ts +0 -28
  65. package/dist/helpers/semantic-input.d.ts.map +0 -1
  66. package/dist/helpers/semantic-input.js +0 -47
  67. package/docs/forms.md +0 -271
@@ -1,100 +1,370 @@
1
- # JSFE reference for flow authors
1
+ # JSFE reference
2
2
 
3
- What a flow author (and the Flow Designer's CoPilot, which reads this file from the published package) needs to know about the engine itself. A host's own platform — its cargo fields, functions and system flows — is described by that host.
3
+ This is the self-contained authoring reference for JSFE and the Flow Designer's backend CoPilot. Use the actual installed flow/tool registries and host instructions for available business services, approved functions, configuration and credentials. Do not invent a tool, shared flow, model role or business capability. This reference describes engine behavior; it does not activate or deploy definitions.
4
4
 
5
- ## JSFE Architecture
5
+ ## 1. Runtime documents and ownership
6
6
 
7
- JSFE is a stack-of-stacks interpreter that executes flows as a plugin in its host site, mediating between a User and a Conversational AI. Flows can be marked as PRIMARY, in which case their description is forwarded (in a menu-like form) to an intent-detection AI to determine whether the most recent user prompt should trigger execution of one of them.
7
+ A flow set is a JSON array, conventionally `tenant.flows`, accompanied by a JSON tool array, `tenant.tools`. These are the editable runtime sources. Include all tenant workers, catalogs, forms, action declarations and named JavaScript functions in those documents. They must not import tenant JavaScript modules or require a generator to reconstruct their definitions. The host may compose multiple matched pairs, such as system, Shopify and tenant sets. Reference installed shared workers by ID instead of copying them. Resolve conflicting IDs deliberately; never rely on a later duplicate silently shadowing a definition.
8
8
 
9
- ## Flow Structure
9
+ JSFE owns collection state, nested ownership, validation transitions, confirmation invalidation, action guards and recovery. The host owns approved transport functions, credentials, storage, turn serialization and model configuration. Tenant definitions own intent descriptions, business rules, API payloads and presentation. Keep generic collection/retrieval/action bookkeeping in JSFE.
10
10
 
11
- A flow is a JSON object with:
12
- - id (string): unique kebab-case identifier
13
- - name (string): PascalCase display name
14
- - version (string): semver
15
- - description (string): CRITICAL — the ONLY text the intent-detection AI reads to decide activation. Must clearly state what SHOULD trigger this flow AND what SHOULD NOT. Include trigger phrases and explicitly negate similar-but-wrong intents.
16
- - prompt / prompt_es (string): short UI label (e.g. "Payment"), NOT a trigger phrase. Used for display: "Flow {prompt} completed"
17
- - primary (boolean): if true, the intent-detection AI can directly activate this flow from user input. If false, the flow is a sub-flow only reachable via FLOW steps from other flows.
18
- - wraps (string, optional): the id or name of a SHARED flow this flow is a thin entry point for. The wrapped flow then stops being primary (it stays a worker), and this flow inherits its description, parameters, prompts and primary flag unless it declares its own. Use it to add a tenant step (a lookup, an argument) in front of a shared flow without copying it; never copy a shared flow to change it.
19
- - parameters (array): values the AI extracts from the user's message on activation, e.g. [{ name: "acct_number", type: "string", description: "..." }]
20
- - enum (string[], optional, string parameters only): the allowed values, e.g. { name: "ticket_type", type: "string", description: "...", enum: ["Fraud", "Cancellation"] }. A reply matching ignoring case becomes the declared spelling; any other value is dropped, so the flow must still ask for it (keep the SAY-GET). Declare one whenever the values are a closed set. Values: non-empty, no leading/trailing spaces, unique ignoring case.
21
- - variables (object): flow-scoped variables { varName: { type, description, value? } } — local to this flow instance
22
- - scope (string, optional): "isolated" makes the flow a self-contained worker: a call (or replace) starts it with ONLY its declared variables and the parameters actually passed (an omitted parameter is undefined, never the caller's or a previous call's value), and its variables never reach the caller — return results through cargo. Default "shared": the caller's variables, by reference. Use "isolated" for generic workers called from many flows.
23
- - steps (array): ordered list of step objects
24
- - comments (string, optional): NOT a flow property — placed on the response wrapper object only
11
+ There are four authoring concepts:
25
12
 
26
- ## Step Types
13
+ | Concept | JSON declaration | Purpose |
14
+ | --- | --- | --- |
15
+ | Form | `form` | Collect and validate a reentrant task, accepting independently valid inputs out of order. |
16
+ | Provider | `provides` | Retrieve declared facts or fact sets, with authentication where required. |
17
+ | Performer | `form` and `performs`, with `prepare` and `present` | Collect, prepare, confirm and execute a guarded action. |
18
+ | Worker | `steps`, or `call` | Perform a small explicit calculation or orchestration task. |
27
19
 
28
- SAY — Outputs the literal string of its VALUE (English) or the respective VALUE_{language-code} (like value_es), which may include {{}} interpolation placeholders that evaluate any valid JavaScript expression. SAY output messages accumulate until the next wait-state (SAY-GET), which will then relay the combined message to the user.
20
+ A versioned entry has `declarationVersion: 1`. JSFE lowers it at engine construction, compiles contextual question workers, links installed child schemas and validates the new declarations. Ordinary executable entries without that marker retain their existing meaning. Generated steps and schemas are execution output, not a second editable source. Keep `declarationVersion: 1` on workers that declare `functions`.
29
21
 
30
- SAY-GET — Same as SAY, but immediately returns control to the user to collect the next prompt into its named VARIABLE property. May include a digits constraint for DTMF input { min, max, autoSubmitChars?, autoSubmitMs? }; on voice a fitting answer is stored as its digits, and on a one-key question (max 1) only an answer that is exactly one key counts as that key. asSpoken: true (or a condition on the flow's variables) stores a voice answer exactly as heard: never reduced to its digits and never sent to the AI voice cleanup. Use it ONLY where that cleanup would lose meaning, such as an amount ("$1" must not become the keypad key 1). Leave it off for names, emails, phone, card and account numbers, codes and yes/no answers: the cleanup is what removes filler ("um, it's Ron") and writes spoken emails and numbers correctly.
22
+ `compileFlowDeclarations(flows, {tools?, externalFlows?, validate?})` is the tooling accessor; validation defaults to true. External flow objects support child-schema linking; external IDs alone support reference checking. A runtime engine must receive the actual complete composed registry. Compilation/contract validation is not behavioral testing.
31
23
 
32
- SET — Evaluates the JavaScript expression in its VALUE property and assigns the result to its named VARIABLE. Can also produce side-effects on cargo (session state) via expressions like cargo.accountNumber = acct_number.
24
+ ## 2. Common flow fields
33
25
 
34
- CASE — Branching mechanism with multiple CONDITION nodes. Each condition key is prefixed with "condition:" followed by a JavaScript expression. Each condition node contains a SINGLE STEP to execute if its expression evaluates to true. A "default" branch is executed if no conditions match. Branch evaluation order matters — first match wins.
26
+ | Field | Meaning |
27
+ | --- | --- |
28
+ | `id` | Stable unique identifier, conventionally kebab-case. |
29
+ | `name` | Activation name, conventionally PascalCase; derived from `id` for declarations when omitted. |
30
+ | `description` | Intent boundary: what should activate the primary and which neighboring requests belong elsewhere. Stage-one intent selection reads this description. |
31
+ | `primary` | Whether intent detection may activate this entry. Ordinary flows default false; Provider defaults true unless overridden. |
32
+ | `version` | Informational flow version; not a saved-session migration or hot-reload instruction. |
33
+ | `scope` | `isolated` or `shared`. Prefer isolated reusable workers. Versioned builders default isolated. |
34
+ | `parameters` | Activation/call inputs. Declare meaning precisely; never infer consent from extraction. |
35
+ | `parameterInstructions` | Cross-parameter extraction guidance for stage two; not stage-one intent selection. |
36
+ | `variables` | Initial local variables, preferably `{ "name": {"type":"string","value":""} }`. Object/array defaults are cloned per activation. |
37
+ | `functions` | Named ordinary JavaScript bodies, described below. |
38
+ | `contract` | Business summary, role, requirements, tool references and result metadata; builders supply normal protocol details. |
39
+ | `wraps` | Ordinary thin wrapper over an installed shared flow, by ID/name. The shared target becomes non-primary; omitted wrapper description, parameters, prompts and primary flag inherit from it. |
35
40
 
36
- SWITCH — Similar to CASE, but branching is based on the value of a single VARIABLE that is evaluated once, then matched against multiple case values. Each case node contains a SINGLE STEP.
41
+ For an ordinary executable flow, `prompt` / `prompt_es` are short UI labels, not intent instructions. For a Form/Performer declaration put them inside `form`. Other supported language variants use the corresponding language suffix.
37
42
 
38
- FLOW — A jump/goto-like mechanism that forwards control to another flow using one of three call types:
39
- 1. call — Equivalent to a typical function call. The callee runs and then returns control to the caller flow's next step. Variable scope is inherited — the child can read and modify the caller's variables.
40
- 2. replace — Replaces the current stack frame, removing the caller flow from the stack and proceeding at the first step of the target flow. Inherits the same scope as the replaced flow. If the caller itself was a callee, then when the replacing flow terminates it returns to the original caller (stack-of-stacks semantics).
41
- 3. reboot — Clears the entire stack of stacks and starts the target flow from its first step as a fresh execution context. Only explicitly passed parameters are available; all other state is cleared (except cargo). SAY text queued before the reboot is delivered with the new flow's output; discardSay: true drops it.
42
- FLOW steps may include a parameters object to pass values: { "retry_flow": "{{retry_flow}}" }.
43
+ A parameter descriptor has `name`, optional `type`, `description`, optional `enum`, `jsonSchema`, `internal`, and declaration-only `default`. Types are `string` (default), `boolean`, `number`, `integer`, `object`, `array`. A parameter map is also supported: a string value is a string parameter description; an object is its descriptor. `default` initializes its local variable and is omitted from extraction metadata. Preserve meaningful defaults such as an explicit confirmation-policy boolean. Do not copy generated `form_instance` bookkeeping into public parameters.
43
44
 
44
- CALL-TOOL — Invokes either a locally defined function (must be in the APPROVED_FUNCTIONS set), or a REST API endpoint. Either must be defined in the toolsRegistry array following the tool definition schema. Includes tool (tool ID), variable (store result), args (template expressions), and an optional onFail node containing a SINGLE STEP to execute if the tool call fails.
45
+ String `enum` values must be nonempty, trimmed and unique ignoring case. Extraction normalizes a case-insensitive match to the declared spelling and drops other values. An absent/invalid extracted parameter must still be collected. `internal:true` excludes a parameter from two-stage user extraction. `jsonSchema` supplies structured extraction shape; a form still validates its individual leaves. Public primary form fields with descriptions derive missing extraction parameters, including nested child schemas; declare aliases or narrower extraction enums explicitly.
45
46
 
46
- RETURN — Unconditionally terminates execution of the entire stack of stacks (full reset), returning control to the JSFE host. The result of evaluating its VALUE expression is returned to the host. If that expression evaluates to '' (empty string), the host will proceed to process the last user prompt that was forwarded to JSFE as input — effectively forwarding to the host AI/RAG. SAY text queued before a RETURN is NOT delivered unless keepSay: true, which delivers it ahead of the value.
47
+ Descriptions identify services and facts; caller-facing wording belongs in questions, SAY steps and fact renderers. Prefer focused handlers for distinct questions instead of one generic summary.
47
48
 
48
- END — Returns from the current flow only, resuming its caller at the step after the FLOW call — a functional return, with no value (a callee shares its caller's variables unless it is isolated; results travel through cargo). In a flow nobody called, it simply ends the flow.
49
+ ## 3. Expressions, variables and named JavaScript
49
50
 
50
- DISPATCH — Ends every flow (all stacks, and any SAY output not yet delivered) and routes the user's input for THIS turn through intent detection, exactly as if no flow had been active: a matching flow starts in the same turn, otherwise the host AI/RAG answers. Takes an id and optionally outcome/reason (no value): the ended flows' outcome reaches the host only when no flow matches. Use it right after a SAY-GET whose answer may really be a new request — e.g. the "default" branch of a menu's CASE, or the answer to "Anything else?" — so the user can move from flow to flow.
51
+ Step expression strings are ordinary JavaScript expressions. `{{expression}}` interpolates a value into a message template. In a SET expression use the comma operator for multiple assignments, or call a named function; do not place bare semicolon-separated statements in an expression. Host-approved helpers and current flow variables are available in expressions. `cargo` is session-persistent state shared across flow boundaries, reboots and returns. It does not replace authentication or input validation.
51
52
 
52
- Conditional handoff — `DISPATCH` may declare `onResponse: "continue"` and a non-empty `responseContext` describing the current requested information. This scoped routing offers a reserved `ContinueCurrent` disposition alongside the primary workflows and `None`: a response (including invalid data or clarification) keeps the live continuation and executes the following authored recovery steps; a named workflow replaces the stacks; an unrelated request with no workflow (`None`) hands off to the host as usual. The decision precedes termination, recovery and outcome stamping, is reused once, and never restores a snapshot. Detection errors propagate with the continuation intact. Ordinary DISPATCH behavior is unchanged when the option is absent.
53
+ An isolated flow receives its own declared variables/defaults and explicitly passed parameters, not arbitrary caller locals. Its local writes do not return to the caller; return domain results through declared cargo paths. Ordinary shared flow calls share the caller context by reference. Do not use `parameter || cargo.value` where false, zero or an empty value has a distinct business meaning; check the intended absence condition explicitly.
53
54
 
54
- Typed contextual response (reviewed, unreleased runtime) — pair `responseParameters: [...]` (primitive `string`/`boolean`/`number`/`integer` parameter descriptors; contextual v1 rejects `object`, `array`, and `jsonSchema`) with `responseVariable: 'response'` (an object variable declared in that flow). The existing extraction stage supplies normalized parameters only when `ContinueCurrent` is chosen; JSFE binds a cloned object before continuing. A named primary or `None` never writes that variable. Missing fields remain missing: the caller must validate completeness and collect/re-ask, never treat the disposition as confirmation or effect authorization. Typed model errors preserve the live step and previous object. Conflicting typed decisions within one turn fail closed.
55
+ A function declaration is:
55
56
 
56
- All explicit contextual steps pass the resolved `responseContext` into detection and any extraction stage without mutating `lastChatTurn`. Native builders derive `jsfe:contextual-responses:v1` and its `contextualResponseProtocol() === 1` entry guard for typed steps; a matched runtime/helper registry is required, with no host flag that can enable unsupported support. Ordinary DISPATCH remains unchanged. See [Typed contextual responses](forms.md#typed-contextual-responses) for the complete contract and a minimal example.
57
+ ```json
58
+ {
59
+ "declarationVersion": 1,
60
+ "id": "calculate-total",
61
+ "description": "Calculate the sum of the supplied item amounts.",
62
+ "functions": {
63
+ "total": {
64
+ "description": "Sum the supplied item amounts without changing them",
65
+ "parameters": [{"name":"items","type":"array"}],
66
+ "body": [
67
+ "let sum = 0;",
68
+ "for (const item of items) sum += Number(item.amount);",
69
+ "return sum;"
70
+ ]
71
+ }
72
+ },
73
+ "steps": [{
74
+ "id":"calculate", "type":"SET", "variable":"noop",
75
+ "value":"(cargo.total = fn.total(cargo.items), true)", "requireTrue":true
76
+ }]
77
+ }
78
+ ```
79
+
80
+ `functions` maps safe JavaScript identifiers to `{parameters, body}`. Each parameter has `name`, optional descriptive `type` / `description`, and optional `rest:true` on a rest parameter. `body` is an array of ordinary JavaScript source lines. Optional function `name` preserves its own recursion name when the registry key is an alias. Argument type annotations are descriptive; business validation remains explicit.
81
+
82
+ Use ordinary `if`, loops, local variables, arrays, objects, callbacks, `map`, `filter`, `reduce` and sibling function calls. This is not a restricted calculation DSL. Bodies are synchronous trusted developer code, compiled once for the loaded owner definition. Expressions call `fn.name(args)`; bodies can call siblings directly or through `fn`. Registered approved platform helpers are lexically available; callbacks may also be explicit parameters. Pass `cargo`, form state, request, result and other session values explicitly: functions do not capture a live session, caller variables or module imports. Function names are scoped to their declaring flow. `fn` is reserved; do not declare a variable, parameter, global or approved helper with that name.
83
+
84
+ Use functions for pure business calculations and guarded session projections. External effects must use registered tools/action workers. Do not hide transport calls, new model selection or action authorization in a helper.
85
+
86
+ ## 4. Ordinary executable steps
87
+
88
+ Each step has `type`, a stable `id`, and the applicable fields below. CASE/SWITCH branches and `onFail` contain one step object, never an array. Use a named worker when a branch needs several steps. Executing a branch does not terminate the following step sequence.
89
+
90
+ | Type | Fields and behavior |
91
+ | --- | --- |
92
+ | `SAY` | `value`, optional `value_es` etc.; append localized text until the next wait/return boundary. |
93
+ | `SAY-GET` | Same message fields plus `variable`; deliver accumulated text and wait for the next answer. Optional `digits`, `asSpoken`, `pii`. |
94
+ | `SET` | Evaluate `value`, assign to `variable`. `requireTrue:true` requires the result to be exactly true; expression failure must not be treated as success. |
95
+ | `CASE` | Ordered `branches` keys `condition: expression`, with optional `default`; first matching condition wins. |
96
+ | `SWITCH` | Evaluate `variable` once; select its value's branch, otherwise `default`. |
97
+ | `FLOW` | `value` target ID/name, `callType`, optional `parameters`; see control semantics below. |
98
+ | `CALL-TOOL` | Registered `tool`, `args`, result `variable`, and explicit `onFail`. |
99
+ | `END` | End only this flow; resume its caller after the FLOW call. A root simply finishes. |
100
+ | `RETURN` | End all stacks and return the evaluated `value` to the host. Empty string forwards this turn's original input to host AI/RAG. Queued SAY text is dropped unless `keepSay:true`. |
101
+ | `DISPATCH` | End all stacks, drop undelivered SAY text, and reroute this turn's input through primary intent detection. A match starts in the same turn; otherwise the host handles it with its conversation context. |
57
102
 
103
+ `FLOW.call` runs the child and returns to the next caller step. `FLOW.replace` replaces only the current frame; when the replacement ends, it returns to the original caller. A shared replace preserves existing variables; `initializeDefaults:true` fills declared target defaults only where a value is undefined. Versioned native builders set this explicitly. An isolated target always has its own declared context. `FLOW.reboot` clears all stacks and starts a new execution context with explicit parameters, preserving cargo. Queued SAY text normally travels with the reboot; `discardSay:true` drops it.
58
104
 
59
- Declared outcome — the step that ends a flow (RETURN, END, DISPATCH or a final SAY) may carry outcome and reason (both accept {{}}): "unresolved" (the user's need was not met; the flow's transaction is marked failed), "deflected" (a decoy flow absorbed a false-positive intent by design), "resolved" (informational). An outcome that interpolates to empty declares nothing. The host reads it to recover from an unresolved ending.
105
+ For validated native `FLOW.parameters` and `CALL-TOOL.args`, interpolation references must be dotted paths such as `{{request.account}}`, not arbitrary expressions. Compute expressions in a preceding SET or named worker. Provider `gateParameters` is an authoring convenience that lowers whole-expression templates to SET steps before the call.
60
106
 
61
- ## Cargo — Session-Persistent State
107
+ `digits` on SAY-GET has `min`, `max`, optional `autoSubmitChars`, `autoSubmitMs`, and host-supported completion hints. A one-key answer must be exactly that key, not digits found inside a sentence. Direct `asSpoken:true` (or a condition string) preserves the original voice answer instead of digit reduction/AI cleanup. Use it for meaning-sensitive answers such as amounts; do not disable normal number/email cleanup indiscriminately. `pii:true` (or a condition) marks sensitive input for engine/host logging safeguards. FORM field spelling is `as_spoken`, not `asSpoken`.
62
108
 
63
- cargo is a session-level object that persists across ALL flows within a chat session. Unlike flow variables which reset on each flow activation, cargo survives flow boundaries, reboots, and returns.
109
+ An `onFail` SAY alone continues into the next step; route to an explicit terminating/recovery worker when continuation would be unsafe. The same is true of a SAY-only CASE branch. Transport retries must not repeat a charge or cancellation merely because a response was lost.
64
110
 
65
- Cargo side-effect pattern — use SET with a dummy variable:
66
- { "type": "SET", "variable": "side_effect", "value": "cargo.accountNumber = acct_number" }
111
+ ## 5. Forms and inputs
112
+
113
+ A form declaration has top-level common fields and `form:{inputs:[...]}`. Do not combine `form` with top-level executable `steps`. Form-specific options belong inside `form`:
114
+
115
+ | Option | Meaning |
116
+ | --- | --- |
117
+ | `inputs` | Ordered field/group/sub-form declarations. Order controls which ready missing field is asked next, not which fields may be accepted. |
118
+ | `before`, `after` | Ordinary step arrays before collection and after completed collection/confirmation. |
119
+ | `validator` | Whole-form validation worker, called with `{form,values}`. |
120
+ | `confirm`, `before_confirm`, `declined` | Confirmation descriptor, preceding steps and declined step array. |
121
+ | `confirmation_condition` | JavaScript expression deciding whether declared confirmation applies; default true. |
122
+ | `stop` | Internal condition used by the collection loop to stop a context service. |
123
+ | `close_on_stop` | Close that stopped service without returning an incomplete child value. |
124
+ | `resume_on_parent_change` | Owner corrections unwind a stale opted-in context and resume the changed ancestor. |
125
+ | `done` | Default true: complete through the shared form-done transition. False leaves deliberate orchestration to the author. |
126
+ | `prompt`, `prompt_es` | UI labels. |
127
+ | `incomplete_outcome` | Explicit business outcome fallback for incomplete optional followups; see recovery. |
128
+ | `on_exhausted` | Bounded recovery worker after validation attempts are exhausted. |
129
+
130
+ Top-level `variables` provides extra form locals. JSFE creates instance IDs, saved arguments, values, validation and confirmation state; do not author copies of these bookkeeping fields.
131
+
132
+ A minimal collecting flow is:
133
+
134
+ ```json
135
+ {
136
+ "declarationVersion":1, "id":"collect-postal-code", "primary":true,
137
+ "description":"Collect the caller's postal code for the requested service.",
138
+ "form":{"inputs":[{"name":"zip","field":"zip","description":"The caller's postal code"}]}
139
+ }
140
+ ```
67
141
 
68
- Multiple assignments MUST use comma operator, NEVER semicolons (semicolons terminate the expression):
69
- { "type": "SET", "variable": "side_effect", "value": "cargo.support_context = 'payment', cargo.support_context_es = 'pago'" }
142
+ Use one of these input shapes:
70
143
 
71
- ## Variables vs Cargo
144
+ | Shape | Fields |
145
+ | --- | --- |
146
+ | Preset field | `name`, `field`; optional overrides. Presets: `phone`, `email`, `zip`, `account_number`, `ssn_last4`, `amount`, `street_address`, `city`, `state`, `card_number`, `card_expiration`, `card_cvv`, `card_zip`. |
147
+ | Inline field | `name`, `profile`, questions and business validation. |
148
+ | Child form | `name`, `form:"installed-child-id"`, optional `parameters`. JSFE links its schema; do not copy the derived `schema` into editable source. |
149
+ | Alternative group | `name`, `any_of:[leaf-or-child declarations]`; optional `exclusive:true`. At least one applicable member satisfies the group; exclusive competing answers require clarification. |
150
+ | Bound requirement | `name`, `bind:"cargo.someVerifiedValue"`; a nonempty, non-false bound value satisfies it. A bound requirement is not a general text collector. |
151
+
152
+ Field options:
153
+
154
+ | Fields | Meaning |
155
+ | --- | --- |
156
+ | `label`, `label_es`; `question`, `question_es`; `retry`, `retry_es` | Names, first prompt and explicit retry wording. Contextual question templates compile to workers automatically. |
157
+ | `description` | Public extraction guidance; `response.description`, when used, describes an open answer. |
158
+ | `when` | Map paths to desired scalar values or arrays; siblings use field names, session paths use `cargo.*`, owner data uses `form.*`. Values prefixed `!` exclude that value. |
159
+ | `unless` | Paths whose populated, non-false value makes the field inapplicable. |
160
+ | `required_when` | Same condition map; a false evaluated condition makes a relevant field optional but still recognizable. Unknown dependencies block completion. |
161
+ | `depends_on` | Committed prerequisites for validation/preparation; their changes invalidate dependents transitively. |
162
+ | `reset_on` | Invalidate when these fields change, without creating a validation prerequisite. |
163
+ | `validator`, `validate_always` | Field validation worker; true explicitly revalidates unchanged values. A validator declaration may use `revalidate:true`. |
164
+ | `prepare`, `refresh`, `after` | Worker before initial validation/prompt, before each prompt, and after acceptance. |
165
+ | `choices_from`, `question_from` | Read prepared choices/question from the owner's `data`; corresponding localized question storage is handled by shared workers. |
166
+ | `digits`, `pii`, `as_spoken` | Collection hints. FORM preserves original speech by default; false explicitly opts into cleanup. |
167
+ | `confirm_against` | Declare overlapping field interpretations that require clarification even when normal current-field priority applies. |
168
+ | `activate`, `activate_on` | Narrow dormant-child activation: proposed controller assignments plus nominated descendant entry paths. Controller and entry validate atomically; a rejected entry must not flip a controller. |
169
+ | `response` | `{description}` on a readable leaf; use existing contextual DISPATCH extraction before accepting an open-ended answer. |
170
+ | `proposal` | Optional approval of an inferred field candidate, independent of final action consent. |
171
+ | `max_misses`, `max_attempts`, `on_exhausted` | Bounds for unreadable responses, validator rejections and deliberate branch recovery. |
172
+
173
+ Profiles:
174
+
175
+ | `profile.kind` | Options |
176
+ | --- | --- |
177
+ | `choice` | `choices:[{key,phrases,label?,label_es?,keys?,exact?,neutral?,negative?,current_only?}]`; optional `accept_other`, `numeric_values`, `narrative`. |
178
+ | `digits` | `min`, `max`: one unambiguous digit run of that length. |
179
+ | `identifier` | `pattern`: permitted account identifier shape. |
180
+ | `pattern` | `regex`, optional `flags`, `group`; optional `accept_other` for the current field only. |
181
+ | `phone`, `email` | Typed readers; email `literal:true` preserves an explicit visible address token in surrounding prose. |
182
+ | `amount` | `min`, `max`, optional `marked:true` or `marked:"out_of_order"`; optional `money:{currency:"USD",cardinals:true,intent:"payment"}`. |
183
+ | `text` | Current-field text fallback; `narrative:true` retains a substantive answer alongside independent structured fields. |
184
+
185
+ `phrases` is the authoring name for matching aliases; `description` explains their meaning. Do not duplicate `words` / `gloss` aliases in new source. Historical executable definitions remain readable with those old keys; new names take precedence.
186
+
187
+ Matching depends on policy. With `exact:true`, a phrase must form the whole normalized answer, allowing the engine's bounded courtesy/affirmation wrappers; questions and additional substantive corrections do not consent. Thus exact `here` does not accept `pay here`. Without exact, ordinary positive named choices may match within an unnegated clause: do not assume whole-answer matching. Keypad aliases, YES and NO-type answers have stricter rules regardless. `keys` are current-field-only whole-answer keypad aliases; they must not steal a monetary answer or identify a different field. `neutral` is not consent. Use exact choices for sensitive finite decisions.
188
+
189
+ JSFE resolves valid current-field evidence first, then a unique match in the nearest owning form, then ancestors; genuine competing claims are clarified. Independent spans can fill independent fields. Typed evidence outranks arbitrary text. `confirm_against` deliberately retains ambiguity. A child result uses the same acceptance/invalidation transition as a leaf. Pending dependent candidates wait for valid prerequisites; invalid data cannot authorize an action. Narrative mode does not turn fragments or bare structured identifiers into business explanations.
190
+
191
+ ## 6. Validation, reentry and contextual uncertainty
72
192
 
73
- - Flow variables are LOCAL to the flow instance, BUT:
74
- - Can be populated via parameters when activated by AI or called by another flow
75
- - Are inherited by child flows called with callType "call"
76
- - Set by SET or SAY-GET in PRECEDING steps of the current flow
77
- - cargo is SESSION-GLOBAL — always available, persists across all flow boundaries
78
- - When a value could come from either source, use: parameterName || cargo.sameName
79
- Example: "value": "acct_number || cargo.accountNumber"
193
+ A field validator receives `{form,input,value,values,reading}` and writes `cargo.inputCheck={ok:true,value?}` or `{ok:false,message?,message_es?}`. Missing/malformed results fail closed. Activation values and conversational answers use the same validation path. `value` may normalize a valid input; never return success for a refusal to satisfy an effect's prerequisites.
80
194
 
81
- ## Best Practices
195
+ A whole-form validator writes `cargo.formCheck={ok:true}` or `{ok:false,invalid:[{name,message?,message_es?}],message?,message_es?}`. Only declared fields may be rejected. The shared loop invalidates the affected branch and reasks; it does not discard independent valid fields.
82
196
 
83
- 1. JSFE is explicitly designed to promote re-use of small worker flows as sub-flows via call/replace/reboot FLOW steps. Prefer composing small, focused flows over building large monolithic ones.
84
- 2. JSFE intentionally restricts logical branches (CASE, SWITCH) and onFail handlers to a SINGLE STEP, to encourage composition via named sub-flows instead of long, unnamed step lists.
85
- 3. Flows advance to the next STEP unconditionally until the end of the flow; therefore, the only valid ways to terminate a flow early are: an END step (back to the caller), a FLOW step with replace or reboot callType, a RETURN step, or a DISPATCH step.
86
- 4. Before asking the user for information, check if it's already available in cargo from a prior interaction. Use CASE at the top of the flow to detect and skip redundant collection.
87
- 5. After collecting key info, store it in cargo via SET side-effects so subsequent flows don't re-ask.
88
- 6. A menu key counts only as the whole answer: compare it exactly (answer.trim() === '1'), never test for a digit inside the answer ("I want to pay 1" is not a key press). On voice, give a one-key question digits { min: 1, max: 1 } and the engine does the same.
89
- 7. FLOW steps must reference flows that EXIST. If your flow needs a sub-flow that doesn't exist yet, include it in your response.
197
+ State lives in `cargo.forms[opaqueInstance]`, owned by a root task or `(parent instance,input slot)`. JSFE maintains values, accepted proofs, pending candidates, dependencies, revisions, attempts, children and confirmation. `cargo.formTasks` identifies active root tasks. Internal `form_instance` resumes saved arguments and progress; context services use `parent_form` without a result slot. Do not write accepted values, approval tokens, revision counters or stack snapshots directly. Use business callback outputs and the shared acceptance path.
90
198
 
91
- ## Patterns to Avoid
199
+ The loop skips accepted data and asks the first ready missing required field. Corrections invalidate dependent evidence and confirmation. With nested tasks, preserve the actual parent/slot rather than using a definition ID as an instance. Do not fabricate a completed child value when it stops, fails or yields.
92
200
 
93
- 1. SAY in an onFail handler — An onFail with a SAY step will display the error message but then continue to the next step, typically leading to unintended behavior. Use FLOW with reboot to a handler, or RETURN.
94
- 2. SAY in a CASE/SWITCH branch — A branch whose only step is SAY will continue execution into the following step. If the flow should terminate at that point, follow it with END (back to the caller) or use RETURN (with a language-aware expression), or FLOW with reboot.
95
- 3. Referencing non-existent flows — Every FLOW step value must be a flow ID that exists. Return an array of flows if new sub-flows are needed.
201
+ ### Retry, yield and recovery
96
202
 
203
+ `max_misses` defaults to two consecutive unreadable answers: clarify the first with explicit retry text or a localized “Sorry, I didn't catch that.” prefix; yield the second utterance to DISPATCH while preserving the draft. Deterministic uncertainty may yield earlier, especially unrecognized monetary instructions. Validator failures use a separate `max_attempts` budget. An out-of-order accepted answer is not a miss. On exhaustion the nearest declared `on_exhausted` receives `{form,input,failed_form,failed_input,reason:"attempts_exhausted"}` and must deliberately recover that branch; it does not receive consent.
97
204
 
98
- ### Optional field assessment (unreleased)
205
+ Use `response:{description}` for open descriptions that need the existing intent/extraction model's interpretation. The prepared question and field description become contextual DISPATCH context. An extracted answer still passes deterministic validation; missing usable data yields with progress saved. A supported different intent routes to that flow; otherwise the host can answer with its full context. No separate field classifier/model role is needed. Do not attempt exhaustive conversational inference with keyword lists.
206
+
207
+ Ordinary DISPATCH is the default uncertainty escape. An explicit contextual DISPATCH may additionally declare the following step fragment (its surrounding flow must declare the response object and supply its own input/recovery steps):
208
+
209
+ ```json
210
+ {
211
+ "id":"interpret-reply", "type":"DISPATCH", "onResponse":"continue",
212
+ "responseContext":"Ask about the shown products or describe a different product.",
213
+ "responseParameters":[{"name":"asked","type":"string","enum":["stock","price","search"],"description":"The requested operation"}],
214
+ "responseVariable":"response"
215
+ }
216
+ ```
217
+
218
+ Declare `response` as a local object variable. Contextual routing offers `ContinueCurrent` along with primaries and `None`. ContinueCurrent retains the live continuation and runs following recovery steps; an optional typed response writes a cloned normalized object before continuing. A named primary replaces the continuation; None hands off. Neither writes that response object. Typed contextual v1 permits primitive string/boolean/number/integer fields, not object/array/jsonSchema. Missing fields remain missing. Errors preserve the pending step and prior object. Context is supplied to that decision without overwriting saved conversation history. This is existing configured intent/extraction, not authorization and not a snapshot restore.
219
+
220
+ ## 7. Providers
221
+
222
+ Declare a catalog once in top-level `provides`, including on a Form/Performer that answers related questions. JSFE derives the public `asked` parameter and mid-form question catalog. Do not maintain a second vocabulary.
223
+
224
+ | Catalog field | Meaning |
225
+ | --- | --- |
226
+ | `subject`, `subject_es`, `name_path` | Human subject and optional cargo path for the person's display name. |
227
+ | `default` | Fact/set key when no explicit question was supplied. |
228
+ | `gate:{flow,verified:[paths]}` | Authentication worker and truthy verification paths required before private facts. |
229
+ | `source:{flow,result,subject?,refresh?}` | Retrieval worker, cargo result path, optional owner identity path; `refresh:"per_turn"` requests refresh on each turn. |
230
+ | `facts` | Nonempty list of fact definitions. |
231
+ | `sets` | `{key,description?,phrases?,facts:[factKeys]}` for related groups of facts. |
232
+ | `menu` | Optional post-answer menu with localized questions, choices and done policy. |
233
+
234
+ A fact has unique `key`, `description`, optional `phrases`, and a `path` within the loaded source or a dedicated `flow`. Optional `public:true` marks genuinely public data; private catalogs need an explicit gate. Presentation uses `label`/`label_es`, `say`/`say_es`, `missing`/`missing_es`, and `format`. Never invent a source value when absent. Money, date, digit and last-four renderers are presentation, not validation or permission.
235
+
236
+ Supported simple `format` names include `money`, `money_nonzero`, `date`, `date_no_year`, `last4`, `digits`. An object format maps result properties to format names. List format uses `{type:"list",item,item_es?,fields?,join?,join_es?}` with `{items}` / `{count}` in the outer template; optional `say_one` / `say_one_es` handles one item. Templates use `{value}`, named result properties and supplied `{name}` / `{label}`. Bracketed optional segments can provide alternatives separated by `|`.
237
+
238
+ `menu` supports `question`, `question_es`, optional voice variants, and `choices:[{key,phrases,exact?,flow?,set?}]`. `set` applies declared cargo assignments before an action route. `done` supports `phrases`, `say`, `say_es`. Keep whole-answer terminal phrases such as “no thanks” separate from a neutral “no” that offers further help. Facts take priority; a declared terminal answer must not be shortened into a different action. Test following-turn choices and facts, not just direct `asked` activations.
239
+
240
+ The shared `provide-data`, `load-source`, `answer-facts` and provider-menu workers gate, load and answer only the requested facts. Top-level `gateParameters` may pass literal data or whole-expression templates to the gate. Refresh clears old results before loading and records freshness only on success. `no_gate` may avoid rerunning a gate only while all declared verification paths still hold. It cannot grant access. Mid-form provider questions preserve the owner and pending verification instead of stacking repeated authentication tasks.
99
241
 
100
- An `ASSESS-INPUT` step validates a field separately from intent routing. Declare an object `variable`, and string templates `value`, `question`, `purpose`, and `acceptance`. The callback receives `task: "assess_input"` and a strict schema for `{ok, disposition}`. Only `{ok: true, disposition: "accept"}` accepts a value; the engine never rewrites the supplied text. Missing callbacks, unavailable models, timeouts, invalid JSON and contradictory verdicts return an unaccepted retry. FORM input `meaning` declarations invoke this generic step; ordinary inputs do not invoke it. See forms.md for the declaration and cancellation/recovery rules.
242
+ ### Provider example: account-info
243
+
244
+ This reduced **composed-registry fragment** uses the existing account-info worker contract: the source produces `cargo.accountInfo.due.amount`. It is not a standalone flow set. Include the real `account-info-gate` and `account-info-load` definitions and their tool dependencies in the installed sets or final output; use a different source path only when its actual output contract declares it.
245
+
246
+ ```json
247
+ {
248
+ "declarationVersion":1, "id":"account-info", "name":"AccountInfo", "primary":true,
249
+ "description":"Answer questions about the verified account amount due; not an instruction to make a payment.",
250
+ "provides":{
251
+ "subject":"account", "default":"due",
252
+ "gate":{"flow":"account-info-gate","verified":["cargo.otpVerified","cargo.authenticatedAccount"]},
253
+ "source":{"flow":"account-info-load","result":"cargo.accountInfo","subject":"cargo.accountNumber","refresh":"per_turn"},
254
+ "facts":[{
255
+ "key":"due", "description":"The payment currently required, not the entire remaining balance",
256
+ "phrases":["amount due","monto por pagar"], "path":"due", "format":{"amount":"money"},
257
+ "say":"The amount due is {amount}.", "say_es":"Lo que tiene por pagar es {amount}."
258
+ }]
259
+ }
260
+ }
261
+ ```
262
+
263
+ ## 8. Performers, confirmation and results
264
+
265
+ A Performer requires `form`, nonempty `performs`, `prepare` worker and `present` worker; optional `project` is a SET-step array. Each action declaration supports:
266
+
267
+ | Action field | Meaning |
268
+ | --- | --- |
269
+ | `action` | Stable business operation name. |
270
+ | `effect` | `read`, `send`, `write`, `charge`, `cancel`, `handoff`. |
271
+ | `when`, `unless` | Applicable action conditions; more than one selected action is an error. |
272
+ | `subject` | Ownership path such as `form.data.account` or `form.data.subject`; bind account/service identity, not an unrelated session flag. |
273
+ | `gate:{flow?,verified:[paths]}` | Execution-time verification; rerun the declared flow before each fresh effect. |
274
+ | `flow`, `tool` | Installed executor worker and/or registered tool identity. |
275
+ | `idempotency`, `reconcile` | Explicit backend policy. Charge/write/send/cancel require at least one; declaring prose alone does not implement backend idempotency. |
276
+ | `confirm:{exact:true}` | Required for charge, cancel or `reversible:false`. This requires a real form confirmation question. |
277
+ | `outcomes` | Map declared executor statuses to business outcomes, including unknown results. |
278
+ | `retry` | Explicit policies: `after:[knownStatuses]`; unknown retry only for SEND with `unknown:"explicit"` and a new accepted recovery choice. |
279
+
280
+ The prepare worker receives `{form}` and writes `cargo.actionRequest` with the exact request. JSFE selects the applicable action, binds request/subject/current input revision, obtains required confirmation and guards execution. An executor returns its normalized business result through `cargo.operationResult`; transport adapters use `{transport:"ok",value}` or the declared failure path. Native execution must distinguish success, explicit refusal/failure and unknown completion. Do not claim success from a timeout, a missing status or a later balance change.
281
+
282
+ `form.confirm` contains localized `question`, `question_es`, optional additional affirmative `phrases`, `clarifications`, `no_keys`, and `interrupts:[{key,phrases,flow,exact?}]`. The default NO key is `2`; override only for a deliberately declared menu. Clarifications ask for explanation without consenting. Interrupt workers receive `{form,event,text}` and must reenter ordinary validation after corrections. An answer containing YES plus a correction or unrelated request is not approval of the old request.
283
+
284
+ An input `proposal` separately asks whether an inferred field value is correct. It is legal only on readable leaves, not group/child/bind nodes. Options are static confirmation fields, `prepare`, `origins:["activation","answer"]`, `when`, `unless`. Its prepare worker receives `{form,input,value,values,reading}` and writes `cargo.proposalCheck` to a confirmation descriptor or explicitly null. A validator may instead return `proposal` inside a successful input check. A descriptor supports question(s), `binding`, affirmative `phrases`, NO keys, clarifications, interrupts and `on_declined`. Missing or malformed decisions fail closed. Field approval is bound to owner, revision, value and business binding; validation reruns before acceptance. It never authorizes the final action. NO cannot commit the candidate; yield cannot be treated as NO.
285
+
286
+ Projectors update session facts/ledgers after execution and during late-result recovery. `project` allows only SET expressions with local temporary destinations; no tool, FLOW or message steps. Available expression locals are `form` (instance ID), `formSnapshot`, `request`, `result`, `key` and current `cargo`. Use named functions, preserve ownership, return true where your projection wrapper requires it, and make ledger changes idempotent by action key. A detached recovery projector receives the recorded snapshot but writes current cargo; it must not replace newer tasks with old state. Projection failure prevents receipt consumption. The presenter receives `{form,request,result}` and owns customer wording and optional next steps. Do not reread an unrelated nested performer's shared last result.
287
+
288
+ Use the same generic registered execution adapters across performers. Generated `operation:<tool-id>` workers are ordinary executable definitions: include them in the tenant/shared JSON set when referenced. Do not generate missing executors from a guessed tool name at runtime.
289
+
290
+ ### Performer example: make-payment
291
+
292
+ This reduced **composed-registry fragment** illustrates action authoring, not a replacement payment implementation. Its real `payment-prepare` worker must set `form.data.account`, build the validated complete request in `cargo.actionRequest`, and prepare the confirmation question. `payment-execute` and `payment-present` must be supplied with their actual registered payment tools and normalized outcome contracts. A complete payment form also declares its account, method, card and other required inputs; do not infer those values or tool result paths from this example. `get-account` is the existing verification worker.
293
+
294
+ ```json
295
+ {
296
+ "declarationVersion":1, "id":"make-payment", "name":"MakePayment", "primary":true,
297
+ "description":"Make a requested account payment after verification and exact confirmation; not a report of an earlier payment.",
298
+ "form":{
299
+ "inputs":[{"name":"amount","profile":{"kind":"amount","min":0.5,"money":{"currency":"USD","cardinals":true,"intent":"payment"}},"question":"How much would you like to pay?"}],
300
+ "confirm":{"question":"{{cargo.paymentConfirmation.question}}","question_es":"{{cargo.paymentConfirmation.question_es}}"}
301
+ },
302
+ "performs":[{
303
+ "action":"curacao_payment", "effect":"charge", "subject":"form.data.account",
304
+ "gate":{"flow":"get-account","verified":["cargo.otpVerified","cargo.authenticatedAccount"]},
305
+ "flow":"payment-execute", "confirm":{"exact":true},
306
+ "reconcile":{"policy":"Hold unknown results for reconciliation; never automatically repeat a charge."},
307
+ "outcomes":{"ok":"resolved","failed":"unresolved","unknown":"unresolved"}
308
+ }],
309
+ "prepare":"payment-prepare", "present":"payment-present",
310
+ "functions":{
311
+ "recordOutcome":{
312
+ "parameters":[{"name":"cargo"},{"name":"result"},{"name":"key"}],
313
+ "body":[
314
+ "if (!key) throw new Error('Missing action key');",
315
+ "cargo.paymentOutcomes ||= {};",
316
+ "if (!Object.hasOwn(cargo.paymentOutcomes, key)) cargo.paymentOutcomes[key] = result.status;",
317
+ "return true;"
318
+ ]
319
+ }
320
+ },
321
+ "project":[{"id":"record-outcome","type":"SET","variable":"noop","value":"fn.recordOutcome(cargo,result,key)","requireTrue":true}]
322
+ }
323
+ ```
324
+
325
+ The action key makes this session projection idempotent; it does not make the payment API idempotent. Declare backend `idempotency` only when the actual API supports the stated key/policy. Otherwise implement and test the declared reconciliation/unknown-result hold. Neither policy wording nor a recorded ledger entry proves a charge succeeded.
326
+
327
+ ## 9. Outcomes, recovery and persistence
328
+
329
+ A terminating step may declare interpolated `outcome` / `reason`: `resolved`, `unresolved`, `deflected`; shared contextual yields use `pending`. Empty interpolation declares nothing. Outcome is business status, not automatic permission or proof of an external effect. Ordinary uncertainty must not be falsely declared “failed; start over.” Optional post-completion forms can retain completion with `incomplete_outcome:{outcome:"resolved",reason:"payment_made"}` or `{from:"declaredObjectParameter"}`. This cannot complete required inputs or authorize effects.
330
+
331
+ Optional step `recovery:{version:1,mode,reason,form?,flow?}` gives host guidance. Modes are `resume`, `restart`, `hold`, `none`; resume requires a real retained owned form and its definition. The engine validates it and exposes a one-turn `lastFlowRecovery`. A matched DISPATCH consumes the old outcome/recovery; a no-match handoff preserves it. Only explicit restart promises starting over. An attempted/unknown effect needs hold, never retry advice. Metadata does not execute recovery by itself.
332
+
333
+ ### Action persistence
334
+
335
+ Durable is the default native action persistence mode. The host must provide its journal/storage and pass `assertFlowHostCapabilities`. A host may explicitly choose `engine.actionPersistence="session-only"`; both modes retain confirmation, ownership, revision, subject and session action guards. A separate `durableActions` requirement cannot be satisfied by session-only. Missing required support rejects activation; intrinsic `jsfe:*` protocols cannot be enabled by arbitrary host booleans.
336
+
337
+ Session-only protects persisted, serialized session progress from reentry/repetition. It does not protect against a successful external effect followed by loss of the updated session, or concurrent forks of an older snapshot. Durable storage and/or recoverable backend idempotency is needed for that failure boundary. Unknown charges/cancellations must never be automatically repeated in either mode.
338
+
339
+ With a durable journal, the host saves the returned full session before acknowledging exact versioned action receipts with `checkpointActionSession`. Failed saves do not release scopes. Compatible late results project into current state without replaying presenters or restoring an old workflow merely because their storage sequence is larger. Recovery identity binds verified runtime bytes and actual flow/tool contracts; a version string alone is insufficient. Identity mismatch, unresolved effects or failed projections preserve holds. Do not change persistence mode for a live conversation or clear holds to manufacture compatibility.
340
+
341
+ For versioned JSON, JSFE generates internal continuation revisions from the entire ordered declaration and named function bodies. Do not author `safetyRevision`. A source change retires obsolete unexecuted continuations before new input; uncertain effects remain preserved/quarantined. This is change detection, not authentication or automatic hot reload. Ordinary executable flows can explicitly use the SDK's revision helper when their host owns that policy.
342
+
343
+ ## 10. Matching tools JSON
344
+
345
+ Every CALL-TOOL/action tool ID must exist in the composed tools array. A tool declares `id`, `name`, `description`, its input `parameters` JSON Schema (or supported `schema` form), and `implementation`.
346
+
347
+ | Tool field | Meaning |
348
+ | --- | --- |
349
+ | `parameters` | `{type:"object",properties,required?,additionalProperties?}`; properties describe actual arguments. |
350
+ | `implementation.type:"local"` | `function` names a host-approved function; no arbitrary function imports. |
351
+ | `implementation.type:"http"` | `url`, `method`, optional `headers`, `contentType`, `pathParams`, `queryParams`, `authentication`, `timeout`, `retries`, `responseMapping`. Credentials belong to approved host configuration. |
352
+ | `implementation.acceptStatus` | Listed non-2xx statuses are business answers: parse/map their body and let the flow inspect it. Other failed statuses follow onFail. |
353
+ | `returns` | JSON Schema of the value delivered after responseMapping. Read it to use real result paths. Optional host validation warns on mismatch without rewriting the result. |
354
+ | `security.rateLimit` | `{requests,window}` when supplied by the host contract. |
355
+
356
+ `responseMapping` supports `jsonPath` (`mappings` of target names to `{path,transform?,fallback?}`), `object` (`mappings`), `array` (`source`, optional `filter`, `itemMapping`, `sort`, `offset`, `limit`, `fallback`), `template` (`template`, optional `dataPath`) and `conditional` (`conditions:[{if,then}]`, optional `else`). Use the actual tool schema/mapping supplied by the host; do not guess backend result fields or invent transform functions. Preserve explicit failure and unknown-result behavior. Native contract validation requires CALL-TOOL to have an onFail route.
357
+
358
+ ## Reference delivery
359
+
360
+ The canonical package file is `jsfe/docs/copilot-reference.md`. In hy-rag-lambdas, `foundation/copilot-reference.js` caches the reference for ten minutes, resolves the latest published JSFE version through npm, retrieves that version's immutable jsDelivr file, and retains the last successful copy in S3 as fallback. A local documentation edit is not active in the backend until JSFE is published and the loader retrieves it. Changes to the backend CoPilot output schema separately require a host deployment. Match generated definitions to the runtime and shared sets actually installed; publication of this reference does not upgrade them.
361
+
362
+ ## 11. Authoring and debugging checklist
363
+
364
+ 1. Specify the primary's intent boundary and extraction semantics, using supplied host/tool contracts. Keep authentication distinct from website login and requested facts distinct from actions.
365
+ 2. Compose an existing shared field/sub-form/provider/executor before adding a tenant copy. Put the complete new tenant definitions and functions in its JSON pair.
366
+ 3. Declare dependencies, ownership, business validators, refusal handling and exact action consent. Keep uncertain conversation with DISPATCH and the host's full context.
367
+ 4. Test actual loaded JSON: happy path, following-turn menus, out-of-order fields, corrections, wrong input, decline, provider/authentication detours, duplicate requests and unknown effects. Assert tool calls and zero unintended effects, not just wording or inventory counts. Use focused tests for a scoped change; broader acceptance must be explicit and source-bound.
368
+ 5. Validate composed references/tools and execute with matching runtime/helpers/shared sets. A successful compiler or exported function unit test does not prove the deployed prompt or journey uses that definition.
369
+
370
+ For debugging, `explainSession(session,{flows,previous?})` reads existing state and identifies the author component, active worker/step, missing input, confirmation, handoff and action hold. An optional previous snapshot adds changed field names without collected values. It is a snapshot/difference, not an event log, authorization decision or extra model role. An empty stack does not prove success. Keep source definitions editable, loaded definitions immutable, and session bookkeeping inside JSFE.
@@ -1,3 +1,11 @@
1
+ ## 1.7.9: simpler authoring and DISPATCH ownership of conversational interpretation
2
+
3
+ The separate input-assessment classifier, model override and ASSESS-INPUT step are removed. Open-ended fields use existing contextual DISPATCH extraction and concise descriptions; an uncertain answer yields to the host with saved progress. Narrative correction phrases and broad payment refusal/tense rules are removed. Strict money reading, exact confirmation, proposal dependencies and action recovery guards remain.
4
+
5
+ Requires matched shared and tenant definitions. Updated safety revisions retire incompatible saved continuations before consuming input and preserve unknown action holds. Old meaning/assessment declarations fail admission rather than silently bypassing validation. This is an intentional removal of the 1.7.8 assessment extension, not a drop-in runtime-only upgrade. Publish and activate the matched shared/tenant definitions together; the runtime alone is not sufficient.
6
+
7
+ The Form, Provider, Performer and Worker authoring facades derive conventional metadata, parameter defaults, extraction descriptions and provider questions. Plain synchronous calculations/projections compile into ordinary guarded JSFE steps; compileExpression centralizes existing compound expression serialization. explainSession reads existing session snapshots and diffs without exposing collected values or introducing state. Runtime execution continues to consume JSON flow/tool sets, with the established shared-set composition.
8
+
1
9
  # Reproducible native JSFE development candidate
2
10
 
3
11
  The native form/performer implementation spans the engine, host and tenant flow generator. Testing an unversioned sibling symlink does not establish that a clean consumer installation will use the same engine.
@@ -20,7 +28,7 @@ Durable restore/project requires an exact identity match for `{protocol:1,runtim
20
28
 
21
29
  Native performer declarations from 1.7.1 include `contract.requires: ['guardedActions']`. `assertFlowHostCapabilities` derives this requirement only from explicit `durableActions:true` (the default execution mode) or explicit `actionPersistence:'session-only'`. A bare `guardedActions:true` cannot bypass policy. Additional explicit `durableActions` requirements, including serialized 1.7.0 performers, remain strict; rebuild the set to select the new host policy. Other declared requirements still need an explicitly supplied boolean capability. The check never enables a capability. The host rejects unmet requirements before constructing an engine. Legacy flows without capability declarations keep the default-off behavior. The flow-set switch preflight uses the same helper; an explicit `--jsfe-policy` JSON file can merge approved policy keys in the same tenant configuration write as the flows and tools. Omitting the option preserves the current policy and rejects a native set when its requirements are unmet. Compression remains a separate storage decision.
22
30
 
23
- Session-only opt-out (1.7.1) requires `config.jsfe.actionPersistence:'session-only'`, no attached journal, and `durableActions` absent or false. The engine defaults to durable and missing storage still fails closed. Session-only retains confirmation, subject, revision, gate and session-owned attempted/completed/unknown guards, but cannot recover an effect after its updated conversation save is lost. It creates no durable receipts or journal traffic. Action-enabled conversations pin their mode before the first effect; changing the mode of an existing conversation or abandoning durable recovery metadata is rejected. Apply the new mode to fresh conversations and keep existing conversations on their original routing. See [session-only semantics](forms.md#explicit-session-only-action-persistence-171).
31
+ Session-only opt-out (1.7.1) requires `config.jsfe.actionPersistence:'session-only'`, no attached journal, and `durableActions` absent or false. The engine defaults to durable and missing storage still fails closed. Session-only retains confirmation, subject, revision, gate and session-owned attempted/completed/unknown guards, but cannot recover an effect after its updated conversation save is lost. It creates no durable receipts or journal traffic. Action-enabled conversations pin their mode before the first effect; changing the mode of an existing conversation or abandoning durable recovery metadata is rejected. Apply the new mode to fresh conversations and keep existing conversations on their original routing. See [session-only semantics](copilot-reference.md#action-persistence).
24
32
 
25
33
  Publishing the package, deploying the host or uploading tenant/system flow sets are separate release actions requiring the owner's authorization. A release should replace local tarball dependencies with the exact published package whose bytes were accepted, and deploy matched host/system/tenant contracts together. No deployment is implied by a passing local candidate.
26
34
 
@@ -75,3 +83,10 @@ Payment interpretation rejects partial cents and card references as replacement
75
83
  Reviewed acceptance: 89 SDK test files; 142 legacy and 142 native flow suites; 626 hermetic and 626 real-model primary executions across 17 primaries and 167 applicable paths. Targeted model probes: consent/intake 229/230, payments 16/16 per flow set, routing 132/132. The one consent deadline safely left input unaccepted with no case filed; its late verdict was retry, and bounded same-source rechecks passed in both flow sets. Original observations remain retained. Customer effects use local stubs; these results do not claim a literal replay of the October 21 production day.
76
84
 
77
85
  Owner authorized publication, exact pins in both consumers, dev host deployment and matching shared/ai-ar-ql activation in all three dev configs with session-only actions. Production deployment and activation are excluded. Shopify Policy remains unchanged with its later review recorded as a tenant TODO. Match runtime, host and regenerated definitions before activation; existing uncertain work must retain its hold.
86
+
87
+
88
+ ## 1.7.10 — self-contained JSON authoring
89
+
90
+ Version-1 JSON flow declarations compile inside JSFE. Tenant JSON contains its forms, providers, performers, workers and ordinary named JavaScript functions; source snapshots remain detached from executable state. Named functions use explicit session arguments and normal JavaScript loops/callbacks. `phrases` and provider `description` are the authoring names; existing executable `words`/`gloss` inputs retain compatibility. Continuation safety revisions are generated internally from source declarations and preserve unknown action holds. The single authoring specification is `docs/copilot-reference.md`, also consumed by the Lambda CoPilot.
91
+
92
+ Owner authorized publication, exact pins in both consumers, dev host deployment and matching shared/ai-ar-ql activation on all three dev configurations with session-only actions. Native Shopify remains composed and Shopify Policy remains unchanged. Production is outside this authorization. Full execution/model replay follows the matched dev activation; local focused results are not relabelled as full published-runtime acceptance.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "1.7.8",
3
+ "version": "1.7.10",
4
4
  "description": "TypeScript workflow engine for conversational/automation apps: multi-flow orchestration, interrupt/resume, stack-based control, robust errors, and flexible tool/REST integration.",
5
5
  "license": "MIT",
6
6
  "author": "Ron Pinkas",
@@ -40,7 +40,6 @@
40
40
  "README.md",
41
41
  "LICENSE",
42
42
  "docs/copilot-reference.md",
43
- "docs/forms.md",
44
43
  "docs/development-release.md"
45
44
  ],
46
45
  "scripts": {
@@ -1,2 +0,0 @@
1
- export const INPUT_ASSESSMENT_SYSTEM: string;
2
- //# sourceMappingURL=semantic-input-prompt.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"semantic-input-prompt.d.ts","sourceRoot":"","sources":["../../src/helpers/semantic-input-prompt.js"],"names":[],"mappings":"AAwJA,6CAA0H"}