jsfe 1.7.9 → 1.7.11

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 (47) hide show
  1. package/README.md +2 -3
  2. package/dist/forms/authoring.d.ts +1 -1
  3. package/dist/forms/authoring.d.ts.map +1 -1
  4. package/dist/forms/authoring.js +7 -6
  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 +1 -1
  11. package/dist/forms/contracts.d.ts.map +1 -1
  12. package/dist/forms/contracts.js +6 -5
  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.js +13 -13
  20. package/dist/forms/identity-flows.js +8 -8
  21. package/dist/forms/index.d.ts +2 -0
  22. package/dist/forms/index.js +2 -0
  23. package/dist/forms/prompt-compiler.d.ts.map +1 -1
  24. package/dist/forms/prompt-compiler.js +5 -1
  25. package/dist/helpers/answer.d.ts +1 -1
  26. package/dist/helpers/answer.js +2 -2
  27. package/dist/helpers/form-sources.js +1 -1
  28. package/dist/helpers/index.d.ts +1 -0
  29. package/dist/helpers/index.d.ts.map +1 -1
  30. package/dist/helpers/index.js +1 -0
  31. package/dist/helpers/match-inputs.js +5 -5
  32. package/dist/helpers/named-functions.d.ts +5 -0
  33. package/dist/helpers/named-functions.d.ts.map +1 -0
  34. package/dist/helpers/named-functions.js +54 -0
  35. package/dist/helpers/proposal-contract.js +4 -4
  36. package/dist/host/capabilities.d.ts.map +1 -1
  37. package/dist/host/capabilities.js +10 -1
  38. package/dist/host/registry-composition.d.ts.map +1 -1
  39. package/dist/host/registry-composition.js +9 -3
  40. package/dist/index.d.ts +13 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +66 -2
  43. package/dist/runtime-identity.js +1 -1
  44. package/docs/copilot-reference.md +336 -66
  45. package/docs/development-release.md +10 -1
  46. package/package.json +1 -2
  47. package/docs/forms.md +0 -309
package/README.md CHANGED
@@ -12,8 +12,7 @@ npm i jsfe
12
12
  - **[JavaScript Flow Engine User Guide](user-guide.md)**
13
13
  - Comprehensive tutorials, examples, and best practices
14
14
  - **[README.md](README.md)** - Technical API reference (this document)
15
- - **[Flow author reference](docs/copilot-reference.md)** - the engine in one page, for flow authors and AI flow generators (shipped in the package; the Flow Designer's CoPilot reads it from the published version, so change it with the engine)
16
- - **[Native forms, providers and performers](docs/forms.md)** - owned reentrant collection, fact catalogs, confirmed effects and durable recovery
15
+ - **[Flow author reference](docs/copilot-reference.md)** - the authoritative engine and JSON authoring specification for flow authors and AI flow generators (shipped in the package; the Flow Designer's CoPilot reads it from the published version, so change it with the engine)
17
16
  - **[Development candidate acceptance](docs/development-release.md)** - reproducible package and cross-repository verification
18
17
  - **[System Flows](docs/system-flows.md)** and **[Shopify Flows](docs/shopify-flows.md)** - the bundled flow and tool libraries in `flows/`, step by step
19
18
 
@@ -772,7 +771,7 @@ return aiResponse;
772
771
  Native FORM collection in 1.7.2 acknowledges an unreadable answer once, then yields the current
773
772
  utterance while retaining its draft. Explicit recovery metadata distinguishes resumption, required
774
773
  restart, unknown-action hold and no promised recovery; business completion remains independent.
775
- See the [retry/yield/recovery contract](docs/forms.md#retry-yield-and-recovery-contract-172).
774
+ See the [retry/yield/recovery contract](docs/copilot-reference.md#retry-yield-and-recovery).
776
775
 
777
776
  ### Host Responsibilities: Tool Calls, Cancellation and Concurrency
778
777
 
@@ -2,7 +2,7 @@
2
2
  * Arguments are developer-authored JavaScript source, never caller text or runtime values.
3
3
  * This advanced helper does not change Worker.calculate's path-only argument validation.
4
4
  */
5
- export function compileExpression(fn: any, ...args: any[]): string;
5
+ export function compileExpression(fn: any, ...args: any[]): any;
6
6
  export function Worker(spec: any): any;
7
7
  export function Provider(spec: any): any;
8
8
  export function Form(spec: any): any;
@@ -1 +1 @@
1
- {"version":3,"file":"authoring.d.ts","sourceRoot":"","sources":["../../src/forms/authoring.js"],"names":[],"mappings":"AAgDA;;;GAGG;AACH,mEAGC;AASD,uCAUC;AACD,yCAA4F;AAC5F,qCAA4F;AAC5F,0CASC"}
1
+ {"version":3,"file":"authoring.d.ts","sourceRoot":"","sources":["../../src/forms/authoring.js"],"names":[],"mappings":"AAiDA;;;GAGG;AACH,gEAGC;AASD,uCAUC;AACD,yCAAiG;AACjG,qCAAiG;AACjG,0CASC"}
@@ -1,6 +1,7 @@
1
1
  /** Concise author declarations compiled to the existing builders. No additional runtime protocol. */
2
2
  import { defineForm, defineProvider, definePerformer, defineWorker } from './contracts.js';
3
3
  import { FIELD_PRESETS } from './flows.js';
4
+ import { captureAuthorSpec, rememberExpression } from './declaration-capture.js';
4
5
  const own = (o, k) => Object.prototype.hasOwnProperty.call(o || {}, k);
5
6
  const namePattern = /^[A-Za-z_$][\w$]*$/;
6
7
  const forbidden = new Set(['__proto__', 'prototype', 'constructor']);
@@ -63,7 +64,7 @@ function functionSource(fn) {
63
64
  export function compileExpression(fn, ...args) {
64
65
  if (args.some(arg => typeof arg !== 'string' || !arg.trim()))
65
66
  fail('expression arguments must be nonempty authored JavaScript expressions');
66
- return `(${functionSource(fn)})(${args.join(',')})`;
67
+ return rememberExpression(`(${functionSource(fn)})(${args.join(',')})`, fn, args);
67
68
  }
68
69
  function expression(fn, args = [], helpers = {}) {
69
70
  if (!Array.isArray(args) || args.some(arg => typeof arg !== 'string' || !/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*$/.test(arg)))
@@ -72,7 +73,7 @@ function expression(fn, args = [], helpers = {}) {
72
73
  fail('invalid helper binding ' + name); return `const ${name}=(${functionSource(helper)});`; }).join('\n');
73
74
  return `(function(){${bindings}return (${functionSource(fn)})(${args.join(',')});})()`;
74
75
  }
75
- const authored = (flow, component) => ({ ...flow, metadata: { ...flow.metadata, authoring: { component } } });
76
+ const authored = (flow, component, spec) => captureAuthorSpec({ ...flow, metadata: { ...flow.metadata, authoring: { component } } }, component, spec);
76
77
  export function Worker(spec) {
77
78
  const { call, calculate, before = [], ...rest } = normalize(spec);
78
79
  if ([call !== undefined, calculate !== undefined, spec.steps !== undefined].filter(Boolean).length > 1)
@@ -90,10 +91,10 @@ export function Worker(spec) {
90
91
  }
91
92
  else if (before.length)
92
93
  rest.steps = [...before, ...(rest.steps || [])];
93
- return authored(defineWorker({ ...rest, contract: { role: 'worker', ...rest.contract } }), 'Worker');
94
+ return authored(defineWorker({ ...rest, contract: { role: 'worker', ...rest.contract } }), 'Worker', spec);
94
95
  }
95
- export function Provider(spec) { return authored(defineProvider(normalize(spec)), 'Provider'); }
96
- export function Form(spec) { return authored(defineForm(normalize(spec, { form: true })), 'Form'); }
96
+ export function Provider(spec) { return authored(defineProvider(normalize(spec)), 'Provider', spec); }
97
+ export function Form(spec) { return authored(defineForm(normalize(spec, { form: true })), 'Form', spec); }
97
98
  export function Performer(spec) {
98
99
  const normalized = normalize(spec, { form: true });
99
100
  if (spec.provides) {
@@ -105,5 +106,5 @@ export function Performer(spec) {
105
106
  fail('invalid projection helper'); return `const ${name}=(${functionSource(fn)});`; }).join('\n');
106
107
  normalized.project = [{ id: spec.id + '_project', type: 'SET', variable: 'noop', value: `(function(){${helpers}if((${functionSource(project.apply)})(cargo,{form:form,formSnapshot:formSnapshot,request:request,result:result,key:key})!==true)throw new Error('Performer projection must return true');return true;})()` }];
107
108
  }
108
- return authored(definePerformer(normalized), 'Performer');
109
+ return authored(definePerformer(normalized), 'Performer', spec);
109
110
  }
@@ -380,8 +380,6 @@ export const FLOWS: {
380
380
  "condition: ac_key === '__elsewhere'": {
381
381
  id: string;
382
382
  type: string;
383
- outcome: string;
384
- reason: string;
385
383
  };
386
384
  "condition: ac_key === '' && ac_other": {
387
385
  id: string;
@@ -392,8 +390,6 @@ export const FLOWS: {
392
390
  "condition: ac_key === ''": {
393
391
  id: string;
394
392
  type: string;
395
- outcome: string;
396
- reason: string;
397
393
  };
398
394
  default: {
399
395
  id: string;
@@ -1 +1 @@
1
- {"version":3,"file":"choice-flow.d.ts","sourceRoot":"","sources":["../../src/forms/choice-flow.js"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAisBE"}
1
+ {"version":3,"file":"choice-flow.d.ts","sourceRoot":"","sources":["../../src/forms/choice-flow.js"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6rBE"}
@@ -4,7 +4,7 @@ export const FLOWS = [
4
4
  "id": "ask-choice",
5
5
  "name": "AskChoice",
6
6
  "version": "1.19.0",
7
- "description": "Worker: ask one question; sets cargo.choice (the matched key, or 'other' with accept_other) and cargo.choiceText. AGENT / 0 reaches a person, EXIT / * ends, a new request is DISPATCHed. With amount: an answer naming an amount returns 'amount' — one marked as money ($, dollars, cents, decimals), or, when it matched no choice, any answer amountInAnswer reads as one (\"109 con 47\"), except an answer with a single digit and no payment verb (\"5\", \"5 please\"), which is a key press (\"pay 5\" is an amount). An exact choice keyed no / decline / done / cancel (or negative) is picked only by its own words and keys, never by a refusal or a deferral. Optional answer_precheck: a caller flow run with { answer } BEFORE the choices are matched; an answer_key it sets wins (the answer_validator contract, which runs only when no choice matched). A caller-set one-time offer (cargo.switchOffer = { text, text_es, words, flow }) is added to the question and consumed by it: an answer in its words runs its flow (reboot) — e.g. ANOTHER ACCOUNT when the account question was skipped (owner 2026-10-17). Optional reask_long: a long answer that matches nothing is asked again once before it is DISPATCHed. Params: question(_es), choices [{key, words, negative?, neutral?}], retry(_es), accept_other, expect ('number' | 'email' | 'contact'), amount, digits, exit_context(_es). With amount: 'marked' (owner 2026-10-18), only a marked amount is one: '$', a dollar or cents word, a decimal, or 'con' / 'and' with two digits ('102 con 21'); a bare number is not.",
7
+ "description": "Worker: ask one question and return cargo.choice plus the original cargo.choiceText. Declared choices, precheck keys and typed answer-validator keys keep priority across both read passes. Exact negative choices accept only their own declared words and keys. With amount, an unowned legacy payment question accepts a complete USD monetary answer or a simple payment instruction through readMoneyAmount; uncertain prose yields to DISPATCH without declaring an action failure. A lone digit keeps the question's keypad policy; amount:'marked' still requires marked money. An owning FORM supplies form_context and performs its own field, correction, provider-question and confirmation matching before deciding to retry or yield, retaining its draft and safety guards. Optional answer_precheck runs before choices; answer_validator runs only when no choice matched. AGENT/0 requests a person; EXIT/* leaves the request; a consumed switch offer routes its declared flow. Params include question(_es), choices [{key,phrases,exact?,negative?,neutral?}], retry(_es), accept_other, expect, amount, digits, exit_context(_es), pii and form_context.",
8
8
  "parameters": [
9
9
  { "name": "form_context", "type": "object", "description": "Optional declared FORM reader context {form,current,names,questions}; valid field readings take precedence over stale verification-code echoes." },
10
10
  {
@@ -22,7 +22,7 @@ export const FLOWS = [
22
22
  {
23
23
  "name": "choices",
24
24
  "type": "array",
25
- "description": "[{key, words}] in priority order",
25
+ "description": "[{key, phrases}] in priority order",
26
26
  "required": true
27
27
  },
28
28
  {
@@ -401,13 +401,13 @@ export const FLOWS = [
401
401
  "id": "ac_match_offer",
402
402
  "type": "SET",
403
403
  "variable": "ac_key",
404
- "value": "ac_offer && Array.isArray(ac_offer.words) && matchesChoice(ac_answer, ac_offer.words) ? '__switch' : ac_key"
404
+ "value": "ac_offer && Array.isArray(ac_offer.phrases ?? ac_offer.words) && matchesChoice(ac_answer, ac_offer.phrases ?? ac_offer.words) ? '__switch' : ac_key"
405
405
  },
406
406
  {
407
407
  "id": "ac_exact_no_own_words",
408
408
  "type": "SET",
409
409
  "variable": "ac_key",
410
- "value": "(function() { var cs = Array.isArray(choices) ? choices : []; var isExactNo = function(c) { return !!c && c.exact === true && (['no', 'decline', 'done', 'cancel'].indexOf(c.key) > -1 || c.negative === true); }; var c = cs.filter(function(x) { return !!x && x.key === ac_key; })[0]; if (!isExactNo(c)) { return ac_key; } else if (pickChoice(ac_answer, [{ key: 'ac_own', words: c.words, exact: true }], false) === 'ac_own') { return ac_key; } else { return pickChoice(ac_answer, cs.filter(function(x) { return !isExactNo(x); }), ac_other); } })()"
410
+ "value": "(function() { var cs = Array.isArray(choices) ? choices : []; var isExactNo = function(c) { return !!c && c.exact === true && (['no', 'decline', 'done', 'cancel'].indexOf(c.key) > -1 || c.negative === true); }; var c = cs.filter(function(x) { return !!x && x.key === ac_key; })[0]; if (!isExactNo(c)) { return ac_key; } else if (pickChoice(ac_answer, [{ key: 'ac_own', phrases: c.phrases ?? c.words, exact: true }], false) === 'ac_own') { return ac_key; } else { return pickChoice(ac_answer, cs.filter(function(x) { return !isExactNo(x); }), ac_other); } })()"
411
411
  },
412
412
  {
413
413
  "id": "ac_init_answer_key",
@@ -446,7 +446,7 @@ export const FLOWS = [
446
446
  "id": "ac_amount_check",
447
447
  "type": "SET",
448
448
  "variable": "ac_key",
449
- "value": "!ac_prechecked && ac_amount && Number.isFinite(amountInAnswer(ac_answer)) && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
449
+ "value": "ac_key !== '' || !ac_amount || (typeof form_context !== 'undefined' && form_context && form_context.form) ? ac_key : (String(ac_answer||'').trim() && !Number.isFinite(readMoneyAmount(ac_answer,{currency:'USD',cardinals:true,intent:'payment'}))) ? '__elsewhere' : (ac_amount && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(readMoneyAmount(ac_answer,{currency:'USD',cardinals:true,intent:'payment'}))))) ? '__amount' : ac_key)"
450
450
  },
451
451
  {
452
452
  "id": "ac_switch_to_text_key",
@@ -572,13 +572,13 @@ export const FLOWS = [
572
572
  "id": "ac_match_again_offer",
573
573
  "type": "SET",
574
574
  "variable": "ac_key",
575
- "value": "ac_offer && Array.isArray(ac_offer.words) && matchesChoice(ac_answer, ac_offer.words) ? '__switch' : ac_key"
575
+ "value": "ac_offer && Array.isArray(ac_offer.phrases ?? ac_offer.words) && matchesChoice(ac_answer, ac_offer.phrases ?? ac_offer.words) ? '__switch' : ac_key"
576
576
  },
577
577
  {
578
578
  "id": "ac_exact_no_own_words_again",
579
579
  "type": "SET",
580
580
  "variable": "ac_key",
581
- "value": "ac_key === '' ? ac_key : (function() { var cs = Array.isArray(choices) ? choices : []; var isExactNo = function(c) { return !!c && c.exact === true && (['no', 'decline', 'done', 'cancel'].indexOf(c.key) > -1 || c.negative === true); }; var c = cs.filter(function(x) { return !!x && x.key === ac_key; })[0]; if (!isExactNo(c)) { return ac_key; } else if (pickChoice(ac_answer, [{ key: 'ac_own', words: c.words, exact: true }], false) === 'ac_own') { return ac_key; } else { return pickChoice(ac_answer, cs.filter(function(x) { return !isExactNo(x); }), ac_other); } })()"
581
+ "value": "ac_key === '' ? ac_key : (function() { var cs = Array.isArray(choices) ? choices : []; var isExactNo = function(c) { return !!c && c.exact === true && (['no', 'decline', 'done', 'cancel'].indexOf(c.key) > -1 || c.negative === true); }; var c = cs.filter(function(x) { return !!x && x.key === ac_key; })[0]; if (!isExactNo(c)) { return ac_key; } else if (pickChoice(ac_answer, [{ key: 'ac_own', phrases: c.phrases ?? c.words, exact: true }], false) === 'ac_own') { return ac_key; } else { return pickChoice(ac_answer, cs.filter(function(x) { return !isExactNo(x); }), ac_other); } })()"
582
582
  },
583
583
  {
584
584
  "id": "ac_init_answer_key_again",
@@ -617,7 +617,7 @@ export const FLOWS = [
617
617
  "id": "ac_amount_check_again",
618
618
  "type": "SET",
619
619
  "variable": "ac_key",
620
- "value": "!ac_prechecked && ac_amount && Number.isFinite(amountInAnswer(ac_answer)) && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
620
+ "value": "ac_key !== '' || !ac_amount || (typeof form_context !== 'undefined' && form_context && form_context.form) ? ac_key : (String(ac_answer||'').trim() && !Number.isFinite(readMoneyAmount(ac_answer,{currency:'USD',cardinals:true,intent:'payment'}))) ? '__elsewhere' : (ac_amount && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(readMoneyAmount(ac_answer,{currency:'USD',cardinals:true,intent:'payment'}))))) ? '__amount' : ac_key)"
621
621
  },
622
622
  {
623
623
  "id": "ac_other_request_check",
@@ -677,9 +677,7 @@ export const FLOWS = [
677
677
  },
678
678
  "condition: ac_key === '__elsewhere'": {
679
679
  "id": "ac_elsewhere",
680
- "type": "DISPATCH",
681
- "outcome": "{{ac_exit_ctx === 'payment' ? 'unresolved' : ''}}",
682
- "reason": "{{ac_exit_ctx === 'payment' ? 'payment_incomplete' : ''}}"
680
+ "type": "DISPATCH"
683
681
  },
684
682
  "condition: ac_key === '' && ac_other": {
685
683
  "id": "ac_return_other",
@@ -689,9 +687,7 @@ export const FLOWS = [
689
687
  },
690
688
  "condition: ac_key === ''": {
691
689
  "id": "ac_other_request",
692
- "type": "DISPATCH",
693
- "outcome": "{{ac_exit_ctx === 'payment' ? 'unresolved' : ''}}",
694
- "reason": "{{ac_exit_ctx === 'payment' ? 'payment_incomplete' : ''}}"
690
+ "type": "DISPATCH"
695
691
  },
696
692
  "default": {
697
693
  "id": "ac_return_choice",
@@ -1 +1 @@
1
- {"version":3,"file":"continuation-safety.d.ts","sourceRoot":"","sources":["../../src/forms/continuation-safety.js"],"names":[],"mappings":"AAGA,kEAQC;AAVM,qDAAsC;AAC7C,8CAA6C,6BAA6B,CAAC"}
1
+ {"version":3,"file":"continuation-safety.d.ts","sourceRoot":"","sources":["../../src/forms/continuation-safety.js"],"names":[],"mappings":"AAIA,kEAQC;AAVM,qDAAsC;AAC7C,8CAA6C,6BAA6B,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { inheritFlowDeclaration } from './declaration-capture.js';
1
2
  /** Opt in deliberately when a safety fix makes old serialized steps unsafe to resume. */
2
3
  export const continuationSafetyProtocol = () => 1;
3
4
  export const CONTINUATION_SAFETY_REQUIREMENT = 'jsfe:continuation-safety:v1';
@@ -10,5 +11,5 @@ export function withSafetyRevision(flow, revision) {
10
11
  // A safety upgrade does not invent a partial declarative FORM contract for legacy workers.
11
12
  if (original)
12
13
  variables.contract = { ...original, value: { ...original.value, requires: [...new Set([...(original.value?.requires || []), CONTINUATION_SAFETY_REQUIREMENT])] } };
13
- return { ...flow, safetyRevision: revision, steps: [guard, ...steps], variables };
14
+ return inheritFlowDeclaration(flow, { ...flow, safetyRevision: revision, steps: [guard, ...steps], variables });
14
15
  }
@@ -1,6 +1,6 @@
1
1
  export function providerQuestions(provides: any): {
2
2
  key: any;
3
- words: any;
3
+ phrases: any;
4
4
  }[];
5
5
  export function providerParameter(provides: any): {
6
6
  name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/forms/contracts.js"],"names":[],"mappings":"AAeA;;;IAGC;AACD;;;;;EAGC;AACD,qGAAqG;AACrG;;QAqCC;AAqBD;;;QAEC;AAgBD;;;;;;;;;QASC;AACD;;;;QAGC;AACD;;;;;;;;QA8BC;AAED,mHAAmH;AACnH,kDAgBC;AAED,+GAA+G;AAC/G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyEC"}
1
+ {"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/forms/contracts.js"],"names":[],"mappings":"AAgBA;;;IAGC;AACD;;;;;EAGC;AACD,qGAAqG;AACrG;;QAqCC;AAqBD;;;QAEC;AAgBD;;;;;;;;;QASC;AACD;;;;QAGC;AACD;;;;;;;;QA8BC;AAED,mHAAmH;AACnH,kDAgBC;AAED,+GAA+G;AAC/G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyEC"}
@@ -1,3 +1,4 @@
1
+ import { inheritFlowDeclaration } from './declaration-capture.js';
1
2
  import { CONTEXTUAL_RESPONSES_REQUIREMENT, hasFormResponse, validateContextualResponseStep, contextualResponseRuntimeSteps } from '../helpers/contextual-response.js';
2
3
  /** Build-time contracts for conversational flows. Transport operations remain registered tools. */
3
4
  import { INPUT_PROPOSALS_REQUIREMENT, hasInputProposals, proposalRuntimeSteps } from './proposal-runtime.js';
@@ -12,12 +13,12 @@ const value = v => ({ type: Array.isArray(v) ? 'array' : v !== null && typeof v
12
13
  const fail = (id, message) => { throw new Error(`Flow contract ${id}: ${message}`); };
13
14
  const stepList = steps => (steps || []).flatMap(step => [step, ...stepList(Object.values(step.branches || {})), ...(step.onFail ? stepList([step.onFail]) : [])]);
14
15
  export function providerQuestions(provides) {
15
- return [...(provides.facts || []), ...(provides.sets || [])].filter(f => (f.words || f.asks || []).length)
16
- .map(f => ({ key: f.key, words: f.words || f.asks }));
16
+ return [...(provides.facts || []), ...(provides.sets || [])].filter(f => (f.phrases ?? f.words ?? f.asks ?? []).length)
17
+ .map(f => ({ key: f.key, phrases: f.phrases ?? f.words ?? f.asks }));
17
18
  }
18
19
  export function providerParameter(provides) {
19
- const entries = [...(provides.facts || []).filter(f => f.gloss || f.asks?.length), ...(provides.sets || [])];
20
- return { name: 'asked', type: 'string', enum: entries.map(f => f.key), description: entries.map(f => `${f.key}: ${f.gloss || (f.asks || []).join('; ') || f.label || f.key}`).join('. ') };
20
+ const entries = [...(provides.facts || []).filter(f => f.description || f.gloss || f.asks?.length), ...(provides.sets || [])];
21
+ return { name: 'asked', type: 'string', enum: entries.map(f => f.key), description: entries.map(f => `${f.key}: ${f.description || f.gloss || (f.asks || []).join('; ') || f.label || f.key}`).join('. ') };
21
22
  }
22
23
  /** Link declarative sub-forms before runtime so any descendant field can receive an early answer. */
23
24
  export function linkFormSchemas(flows, { externalFlows = [] } = {}) {
@@ -70,7 +71,7 @@ export function linkFormSchemas(flows, { externalFlows = [] } = {}) {
70
71
  }
71
72
  const linked = { ...flow, parameters, variables: { ...flow.variables, inputs: { ...flow.variables.inputs, value: inputs } } };
72
73
  // Descendant schemas are linked after declaration; propagate their runtime requirement to the root entry.
73
- return flow.variables?.contract ? declared(linked, flow.variables.contract.value) : { ...linked, steps: proposalRuntimeSteps(flow.id, linked.steps, hasInputProposals(inputs) ? [INPUT_PROPOSALS_REQUIREMENT] : []) };
74
+ return inheritFlowDeclaration(flow, flow.variables?.contract ? declared(linked, flow.variables.contract.value) : { ...linked, steps: proposalRuntimeSteps(flow.id, linked.steps, hasInputProposals(inputs) ? [INPUT_PROPOSALS_REQUIREMENT] : []) });
74
75
  });
75
76
  }
76
77
  function declared(flow, contract) {
@@ -0,0 +1,7 @@
1
+ export function copyAuthorSpec(value: any): any;
2
+ export function captureAuthorSpec(flow: any, component: any, spec: any): any;
3
+ export function capturedAuthorSpec(flow: any): any;
4
+ export function rememberExpression(source: any, fn: any, args: any): any;
5
+ export function authoredExpressions(): Map<any, any>;
6
+ export function inheritFlowDeclaration(source: any, target: any): any;
7
+ //# sourceMappingURL=declaration-capture.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"declaration-capture.d.ts","sourceRoot":"","sources":["../../src/forms/declaration-capture.js"],"names":[],"mappings":"AAEA,gDAIC;AACD,6EAAgJ;AAChJ,mDAAqE;AACrE,yEAAoK;AACpK,qDAA0D;AAE1D,sEAA4I"}
@@ -0,0 +1,15 @@
1
+ /** Authoring migration support. Captures live functions without putting executable objects in JSON. */
2
+ const originals = new WeakMap(), expressions = new Map();
3
+ export function copyAuthorSpec(value) {
4
+ if (Array.isArray(value))
5
+ return value.map(copyAuthorSpec);
6
+ if (value && typeof value === 'object')
7
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyAuthorSpec(item)]));
8
+ return value;
9
+ }
10
+ export function captureAuthorSpec(flow, component, spec) { const saved = { component, spec: copyAuthorSpec(spec) }; originals.set(flow, saved); return flow; }
11
+ export function capturedAuthorSpec(flow) { return originals.get(flow); }
12
+ export function rememberExpression(source, fn, args) { expressions.set(source, { source: Function.prototype.toString.call(fn), name: fn.name, args: [...args] }); return source; }
13
+ export function authoredExpressions() { return expressions; }
14
+ export function inheritFlowDeclaration(source, target) { const saved = originals.get(source); if (saved)
15
+ originals.set(target, saved); return target; }
@@ -0,0 +1,20 @@
1
+ /** Compile only explicitly versioned declarations. Ordinary executable JSON is unchanged.
2
+ * @param {any[]} flows
3
+ * @param {{tools?: any[], externalFlows?: any[], validate?: boolean}} options
4
+ * @returns {any[]}
5
+ */
6
+ export function compileFlowDeclarations(flows: any[], { tools, externalFlows, validate }?: {
7
+ tools?: any[];
8
+ externalFlows?: any[];
9
+ validate?: boolean;
10
+ }): any[];
11
+ /** Return the original programmatic declaration, even after ordinary spread/clone transformations. */
12
+ export function captureOriginalDeclaration(flow: any): {
13
+ component: any;
14
+ spec: any;
15
+ } | null;
16
+ /** One-time migration of an authored builder to the editable, self-contained JSON format. */
17
+ export function serializeFlowDeclaration(flow: any, { resolvedFlow }?: {
18
+ resolvedFlow?: any;
19
+ }): any;
20
+ //# sourceMappingURL=declarations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"declarations.d.ts","sourceRoot":"","sources":["../../src/forms/declarations.js"],"names":[],"mappings":"AAcA;;;;GAIG;AACH,+CAJW,GAAG,EAAE,uCACL;IAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAC;IAAC,aAAa,CAAC,EAAE,GAAG,EAAE,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAC,GACxD,GAAG,EAAE,CAwCjB;AAED,sGAAsG;AACtG;;;SAAqK;AAuBrK,6FAA6F;AAC7F;;QAuCC"}
@@ -0,0 +1,272 @@
1
+ /** JSON declarations lower through the same authoring builders as programmatic declarations. */
2
+ import { Form, Provider, Performer, Worker } from './authoring.js';
3
+ import { linkFormSchemas, validateFlowContracts } from './contracts.js';
4
+ import { compileFormPrompts } from './prompt-compiler.js';
5
+ import { withSafetyRevision } from './continuation-safety.js';
6
+ import { capturedAuthorSpec, copyAuthorSpec, authoredExpressions } from './declaration-capture.js';
7
+ const formKeys = new Set(['inputs', 'before', 'after', 'confirm', 'before_confirm', 'declined', 'stop', 'close_on_stop', 'resume_on_parent_change', 'done', 'validator', 'confirmation_condition', 'prompt', 'prompt_es', 'incomplete_outcome', 'on_exhausted']);
8
+ const sharedKeys = ['id', 'name', 'description', 'version', 'scope', 'primary', 'parameters', 'contract', 'parameterInstructions'];
9
+ const safe = /^[A-Za-z_$][\w$]*$/;
10
+ const fail = message => { throw new Error('Flow declaration: ' + message); };
11
+ // Trusted-author change detection, not an authentication signature. Stable in browsers and Node.
12
+ function sourceRevision(source) { const text = JSON.stringify(source); const hashes = [2166136261, 2246822507, 3266489909, 668265263]; for (let i = 0; i < text.length; i++)
13
+ for (let lane = 0; lane < hashes.length; lane++)
14
+ hashes[lane] = Math.imul(hashes[lane] ^ text.charCodeAt(i), 16777619 + lane * 2) >>> 0; return hashes.map(n => n.toString(16).padStart(8, '0')).join(''); }
15
+ const variableDeclaration = value => value && typeof value === 'object' && !Array.isArray(value) && ['string', 'number', 'integer', 'boolean', 'object', 'array'].includes(value.type) ? value : { type: Array.isArray(value) ? 'array' : value === null || typeof value === 'object' ? 'object' : typeof value, value };
16
+ /** Compile only explicitly versioned declarations. Ordinary executable JSON is unchanged.
17
+ * @param {any[]} flows
18
+ * @param {{tools?: any[], externalFlows?: any[], validate?: boolean}} options
19
+ * @returns {any[]}
20
+ */
21
+ export function compileFlowDeclarations(flows, { tools, externalFlows = [], validate = true } = {}) {
22
+ if (!Array.isArray(flows))
23
+ fail('flows must be an array');
24
+ if (!flows.some(flow => flow?.declarationVersion !== undefined))
25
+ return flows;
26
+ const ids = new Set();
27
+ for (const flow of flows) {
28
+ if (ids.has(flow.id))
29
+ fail('duplicate flow id ' + flow.id);
30
+ ids.add(flow.id);
31
+ }
32
+ const compiled = flows.map(source => {
33
+ if (source.declarationVersion === undefined)
34
+ return source;
35
+ if (source.declarationVersion !== 1)
36
+ fail('unsupported declarationVersion on ' + source.id);
37
+ const { declarationVersion, form, functions, safetyRevision, ...rest } = structuredClone(source);
38
+ if (Object.hasOwn(source, 'form') && (!form || typeof form !== 'object' || !Array.isArray(form.inputs)))
39
+ fail(source.id + ' form requires inputs');
40
+ if (form && [...formKeys].some(key => Object.hasOwn(rest, key)))
41
+ fail(source.id + ' form options must be inside form');
42
+ if (form && rest.steps)
43
+ fail(source.id + ' cannot combine form and executable steps');
44
+ if (rest.performs && !form)
45
+ fail(source.id + ' performs requires form');
46
+ if (functions !== undefined && (!functions || Array.isArray(functions) || typeof functions !== 'object'))
47
+ fail(source.id + ' functions must be a map');
48
+ const spec = form ? { ...rest, ...form, extraVars: Object.fromEntries(Object.entries(rest.variables || {}).map(([name, value]) => [name, value && typeof value === 'object' && Object.hasOwn(value, 'value') ? value.value : value])) } : rest;
49
+ if (form)
50
+ delete spec.variables;
51
+ let flow = rest.performs ? Performer(spec) : form ? Form(spec) : rest.provides ? Provider(spec) : Worker(spec);
52
+ const parameterNames = new Set();
53
+ flow = { ...flow, parameters: (flow.parameters || []).filter(parameter => { if (parameterNames.has(parameter.name))
54
+ return false; parameterNames.add(parameter.name); return true; }), ...(rest.parameterInstructions !== undefined ? { parameterInstructions: rest.parameterInstructions } : {}), ...(functions ? { functions } : {}), metadata: { ...flow.metadata, declaration: { version: 1, source: source.id } } };
55
+ // Revisions are engine bookkeeping; a stale authored token cannot override source change detection.
56
+ const { safetyRevision: ignoredRevision, ...revisionSource } = source;
57
+ return withSafetyRevision(flow, 'declaration-v1:' + sourceRevision(revisionSource));
58
+ });
59
+ const externalObjects = externalFlows.filter(flow => flow && typeof flow === 'object');
60
+ const formIds = new Set(flows.filter(flow => flow.declarationVersion === 1 && flow.form).map(flow => flow.id));
61
+ const prompted = compileFormPrompts(compiled.filter(flow => formIds.has(flow.id)));
62
+ const promptOwners = new Map(prompted.filter(flow => formIds.has(flow.id)).map(flow => [flow.id, flow]));
63
+ const generated = prompted.filter(flow => !formIds.has(flow.id));
64
+ const installedIds = new Set([...ids, ...externalFlows.map(flow => typeof flow === 'string' ? flow : flow.id)]);
65
+ for (const worker of generated) {
66
+ if (installedIds.has(worker.id))
67
+ fail('generated question worker id collision ' + worker.id);
68
+ installedIds.add(worker.id);
69
+ }
70
+ const linked = linkFormSchemas([...compiled.map(flow => promptOwners.get(flow.id) || flow), ...generated], { externalFlows: externalObjects });
71
+ if (validate) {
72
+ const declaredIds = new Set([...flows.filter(flow => flow.declarationVersion === 1).map(flow => flow.id), ...generated.map(flow => flow.id)]);
73
+ // Loading a declaration must not opt unrelated executable host/shared flows into authoring contracts.
74
+ const declared = linked.filter(flow => declaredIds.has(flow.id));
75
+ const installed = [...externalFlows.map(flow => typeof flow === 'string' ? flow : flow.id), ...linked.filter(flow => !declaredIds.has(flow.id)).map(flow => flow.id)];
76
+ validateFlowContracts(declared, tools || [], { externalFlows: [...new Set(installed)] });
77
+ }
78
+ return linked;
79
+ }
80
+ /** Return the original programmatic declaration, even after ordinary spread/clone transformations. */
81
+ export function captureOriginalDeclaration(flow) { const saved = capturedAuthorSpec(flow); return saved ? { component: saved.component, spec: copyAuthorSpec(saved.spec) } : null; }
82
+ function splitParameters(text) {
83
+ const parts = [];
84
+ let start = 0, depth = 0, quote = '', escape = false;
85
+ for (let i = 0; i < text.length; i++) {
86
+ const c = text[i];
87
+ if (quote) {
88
+ if (escape)
89
+ escape = false;
90
+ else if (c === '\\')
91
+ escape = true;
92
+ else if (c === quote)
93
+ quote = '';
94
+ continue;
95
+ }
96
+ if ('"\'`'.includes(c)) {
97
+ quote = c;
98
+ continue;
99
+ }
100
+ if ('([{'.includes(c))
101
+ depth++;
102
+ if (')]}'.includes(c))
103
+ depth--;
104
+ if (c === ',' && !depth) {
105
+ parts.push(text.slice(start, i).trim());
106
+ start = i + 1;
107
+ }
108
+ }
109
+ if (text.slice(start).trim())
110
+ parts.push(text.slice(start).trim());
111
+ return parts;
112
+ }
113
+ /** Ordinary synchronous JavaScript source becomes named parameters and body lines, not a new language. */
114
+ function functionDefinition(fn) {
115
+ if (typeof fn !== 'function' && !(fn && typeof fn.source === 'string'))
116
+ fail('only synchronous JavaScript functions can be serialized');
117
+ if (typeof fn === 'function' && fn.constructor.name !== 'Function')
118
+ fail('only synchronous JavaScript functions can be serialized');
119
+ const source = (typeof fn === 'function' ? Function.prototype.toString.call(fn) : fn.source).trim();
120
+ let parameters, body;
121
+ if (/^(?:function\b|[A-Za-z_$][\w$]*\s*\()/.test(source)) {
122
+ const start = source.indexOf('(');
123
+ let depth = 1, end = start + 1, quote = '';
124
+ for (; end < source.length; end++) {
125
+ const c = source[end];
126
+ if (quote) {
127
+ if (c === quote && source[end - 1] !== '\\')
128
+ quote = '';
129
+ continue;
130
+ }
131
+ if ('"\'`'.includes(c)) {
132
+ quote = c;
133
+ continue;
134
+ }
135
+ if (c === '(')
136
+ depth++;
137
+ if (c === ')' && !--depth)
138
+ break;
139
+ }
140
+ parameters = splitParameters(source.slice(start + 1, end));
141
+ const open = source.indexOf('{', end);
142
+ body = source.slice(open + 1, source.lastIndexOf('}'));
143
+ }
144
+ else {
145
+ const arrow = source.indexOf('=>');
146
+ if (arrow < 0)
147
+ fail('unsupported function source');
148
+ let head = source.slice(0, arrow).trim();
149
+ if (head.startsWith('('))
150
+ head = head.slice(1, -1);
151
+ parameters = splitParameters(head);
152
+ const tail = source.slice(arrow + 2).trim();
153
+ body = tail.startsWith('{') ? tail.slice(1, -1) : 'return (' + tail + ');';
154
+ }
155
+ const prelude = [];
156
+ const used = new Set(parameters.filter(p => safe.test(p)));
157
+ const args = parameters.map((raw, i) => { if (safe.test(raw))
158
+ return { name: raw }; let name = 'argument' + i; while (used.has(name))
159
+ name += '_'; used.add(name); if (raw.startsWith('...')) {
160
+ const target = raw.slice(3);
161
+ prelude.push('const ' + target + ' = ' + name + ';');
162
+ return { name, rest: true };
163
+ } let depth = 0, equals = -1; for (let j = 0; j < raw.length; j++) {
164
+ if ('([{'.includes(raw[j]))
165
+ depth++;
166
+ else if (')]}'.includes(raw[j]))
167
+ depth--;
168
+ else if (raw[j] === '=' && !depth) {
169
+ equals = j;
170
+ break;
171
+ }
172
+ } if (equals >= 0) {
173
+ const binding = raw.slice(0, equals).trim();
174
+ prelude.push('let ' + binding + ' = ' + name + ' === undefined ? (' + raw.slice(equals + 1) + ') : ' + name + ';');
175
+ }
176
+ else
177
+ prelude.push('const ' + raw + ' = ' + name + ';'); return { name }; });
178
+ return { ...(fn.name && safe.test(fn.name) ? { name: fn.name } : {}), parameters: args, body: [...prelude, ...body.trim().split('\n')] };
179
+ }
180
+ /** One-time migration of an authored builder to the editable, self-contained JSON format. */
181
+ export function serializeFlowDeclaration(flow, { resolvedFlow = flow } = {}) {
182
+ const saved = capturedAuthorSpec(flow);
183
+ if (!saved)
184
+ return structuredClone(resolvedFlow);
185
+ const spec = copyAuthorSpec(saved.spec), registry = {}, sources = new Map();
186
+ const register = (fn, preferred) => {
187
+ const source = typeof fn === 'function' ? Function.prototype.toString.call(fn) : fn.source;
188
+ let name = preferred || fn.name || 'calculation';
189
+ if (!safe.test(name))
190
+ name = 'calculation';
191
+ let suffix = 2;
192
+ while (registry[name] && sources.get(name) !== source)
193
+ name = (preferred || fn.name || 'calculation') + '_' + suffix++;
194
+ if (!registry[name]) {
195
+ registry[name] = functionDefinition(fn);
196
+ sources.set(name, source);
197
+ }
198
+ return name;
199
+ };
200
+ const helpers = items => { for (const [name, fn] of Object.entries(items || {}))
201
+ register(fn, name); };
202
+ const rewrite = value => {
203
+ if (typeof value === 'string') {
204
+ // Outer expressions first: their arguments can themselves contain authored expressions.
205
+ for (const [source, entry] of [...authoredExpressions()].sort((a, b) => b[0].length - a[0].length))
206
+ if (value.includes(source)) {
207
+ const name = register(entry);
208
+ value = value.split(source).join('fn.' + name + '(' + entry.args.map(rewrite).join(',') + ')');
209
+ }
210
+ return value;
211
+ }
212
+ if (typeof value === 'function')
213
+ fail('a function must be a declared calculation, projection or helper');
214
+ if (Array.isArray(value))
215
+ return value.map(rewrite);
216
+ if (value && typeof value === 'object')
217
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, rewrite(item)]));
218
+ return value;
219
+ };
220
+ helpers(spec.helpers);
221
+ if (spec.calculate) {
222
+ const c = spec.calculate;
223
+ helpers(c.helpers);
224
+ const name = register(c.value);
225
+ spec.steps = [...(spec.before || []), { id: spec.id + '_calculate', type: 'SET', variable: 'noop', value: `(${c.result}=fn.${name}(${(c.args || []).join(',')}),true)`, requireTrue: true }];
226
+ spec.contract = { result: { path: c.result, type: 'object' }, ...spec.contract };
227
+ delete spec.calculate;
228
+ delete spec.before;
229
+ }
230
+ if (spec.project && !Array.isArray(spec.project)) {
231
+ helpers(spec.project.helpers);
232
+ const name = register(spec.project.apply);
233
+ spec.project = [{ id: spec.id + '_project', type: 'SET', variable: 'noop', value: `(function(){if(fn.${name}(cargo,{form:form,formSnapshot:formSnapshot,request:request,result:result,key:key})!==true)throw new Error('Performer projection must return true');return true;})()` }];
234
+ }
235
+ const result = { declarationVersion: 1 };
236
+ for (const key of sharedKeys)
237
+ if (spec[key] !== undefined)
238
+ result[key] = spec[key];
239
+ for (const key of ['name', 'description', 'parameters', 'primary', 'scope', 'parameterInstructions'])
240
+ if (resolvedFlow[key] !== undefined)
241
+ result[key] = structuredClone(resolvedFlow[key]);
242
+ const originalParameters = Array.isArray(spec.parameters) ? spec.parameters : Object.entries(spec.parameters || {}).map(([name, value]) => ({ name, ...(typeof value === 'object' ? value : {}) }));
243
+ const serializedParameterNames = new Set();
244
+ if (result.parameters)
245
+ result.parameters = result.parameters.filter(parameter => { if (serializedParameterNames.has(parameter.name))
246
+ return false; serializedParameterNames.add(parameter.name); return true; }).filter(parameter => parameter.name !== 'form_instance' || originalParameters.some(original => original.name === 'form_instance')).map(parameter => { const original = originalParameters.find(p => p.name === parameter.name); return original && Object.hasOwn(original, 'default') ? { ...parameter, default: original.default } : parameter; });
247
+ const isForm = saved.component === 'Form' || saved.component === 'Performer';
248
+ if (isForm) {
249
+ result.form = {};
250
+ for (const key of formKeys)
251
+ if (spec[key] !== undefined)
252
+ result.form[key] = spec[key];
253
+ // Captured inputs are the authoring source; schema linking and question workers are derived on activation.
254
+ for (const key of ['prompt', 'prompt_es'])
255
+ if (resolvedFlow[key] !== undefined)
256
+ result.form[key] = resolvedFlow[key];
257
+ result.variables = Object.fromEntries(Object.entries(spec.extraVars || {}).map(([name, value]) => [name, variableDeclaration(value)]));
258
+ }
259
+ else if (spec.variables)
260
+ result.variables = spec.variables;
261
+ for (const [key, value] of Object.entries(spec))
262
+ if (!sharedKeys.includes(key) && !['extraVars', 'variables', 'helpers', 'safetyRevision'].includes(key) && !(isForm && formKeys.has(key)))
263
+ result[key] = value;
264
+ const out = rewrite(result);
265
+ // Helpers and bodies can reference other explicitly authored expressions as well.
266
+ for (const definition of Object.values(registry))
267
+ definition.body = definition.body.map(rewrite);
268
+ if (Object.keys(registry).length)
269
+ out.functions = registry;
270
+ JSON.stringify(out);
271
+ return out;
272
+ }