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
@@ -105,7 +105,7 @@ export function formFlow({ id, name, version, description, inputs, after = [], e
105
105
  // FLOW parameters are paths only: the question is built here, as a SAY-style template, then passed by name
106
106
  SET(`${id}_confirm_q`, 'form_confirm_q', textValue(confirm.question)),
107
107
  SET(`${id}_confirm_q_es`, 'form_confirm_q_es', textValue(confirm.question_es || confirm.question)),
108
- FLOW(`${id}_confirm`, 'confirm-form', 'call', { form: '{{form_instance}}', question: '{{form_confirm_q}}', question_es: '{{form_confirm_q_es}}', words: '{{form_confirmation.words}}', clarifications: '{{form_confirmation.clarifications}}', no_keys: '{{form_confirmation.no_keys}}', interrupts: '{{form_confirmation.interrupts}}', exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
108
+ FLOW(`${id}_confirm`, 'confirm-form', 'call', { form: '{{form_instance}}', question: '{{form_confirm_q}}', question_es: '{{form_confirm_q_es}}', phrases: '{{form_confirmation.phrases}}', words: '{{form_confirmation.words}}', clarifications: '{{form_confirmation.clarifications}}', no_keys: '{{form_confirmation.no_keys}}', interrupts: '{{form_confirmation.interrupts}}', exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
109
109
  { id: `${id}_confirmed`, type: 'CASE', branches: {
110
110
  [`condition: (cargo.formConfirm || {})[form_instance] === 'changed'`]: FLOW(`${id}_again`, id, 'replace', { parent_form: '{{parent_form}}', result_input: '{{result_input}}', form_instance: '{{form_instance}}' }),
111
111
  // NO: the declined flow takes the form's place, so the action below never runs
@@ -305,7 +305,7 @@ const validateBatch = {
305
305
  SET('vb_outcome', 'vb_outcome', "vb_known ? 'known' : (hasFormValue(vb_values[vb_h.name]) && !formValuesEqual(vb_values[vb_h.name],vb_h.value) ? 'changed' : (vb_h.current ? 'stored' : 'taken'))"),
306
306
  SIDE('vb_reset', "(cargo.inputCheck = vb_h.invalid ? { ok: false } : (vb_h.validator && !vb_known ? null : { ok: true, value: vb_h.value }), true)"),
307
307
  SET('vb_response', 'vb_response', "(function(){var state=cargo.forms[vb_h.form],spec=state && state.specs.flatMap(function(s){return s.any_of || [s];}).find(function(s){return s.name===vb_h.name;});return spec && spec.response || null;})()"),
308
- WHEN('vb_contextual_needed', "vb_ready === true && vb_response && !vb_known && !vb_h.invalid && vb_h.origin !== 'activation' && !vb_h.fromPending", FLOW('vb_read_response', 'read-form-response', 'call', { form: '{{vb_h.form}}', input: '{{vb_h.name}}' })),
308
+ WHEN('vb_contextual_needed', "vb_ready === true && vb_h.current && vb_response && !vb_known && !vb_h.invalid && vb_h.origin !== 'activation' && !vb_h.fromPending", FLOW('vb_read_response', 'read-form-response', 'call', { form: '{{vb_h.form}}', input: '{{vb_h.name}}' })),
309
309
  WHEN('vb_validator', 'vb_ready === true && vb_h.validator && !vb_known && !vb_h.invalid', FLOW('vb_validate', '{{vb_h.validator}}', 'call', { form: '{{vb_h.form}}', input: '{{vb_h.name}}', value: '{{vb_h.value}}', values: '{{vb_values}}', reading: '{{vb_h}}' })),
310
310
  WHEN('vb_refused', 'vb_h.refused === true || vb_h.incompleteMoney === true', SIDE('vb_withhold_refusal', "(cargo.inputCheck=Object.assign({},cargo.inputCheck || {},{ok:false}),true)")),
311
311
  SET('vb_candidate', 'vb_candidate', "Object.assign({},vb_h,{ok:!!(cargo.inputCheck && cargo.inputCheck.ok === true),value:cargo.inputCheck && cargo.inputCheck.value !== undefined && cargo.inputCheck.value !== null ? cargo.inputCheck.value : vb_h.value,message:cargo.inputCheck && cargo.inputCheck.message,message_es:cargo.inputCheck && cargo.inputCheck.message_es})"),
@@ -393,7 +393,7 @@ const disambiguate = {
393
393
  steps: [
394
394
  WHEN('di_store_clear', 'Array.isArray(hits) && hits.length > 0', FLOW('di_store_hits', 'collect-input-accept', 'call', { hits: '{{hits}}' })),
395
395
  SET('di_number', 'di_keys', `${KEYS_JS}(readings.length)`),
396
- SET('di_build', 'di_choices', "readings.map(function (r, i) { var own = String(r.label + ' ' + r.label_es).toLowerCase().split(/\\s+/).filter(function (w) { return w.length > 3 && !readings.some(function (o, j) { return j !== i && String(o.label + ' ' + o.label_es).toLowerCase().split(/\\s+/).indexOf(w) > -1; }); }); return { key: 'r' + i, words: [di_keys[i], r.label, r.label_es].concat(own) }; })"),
396
+ SET('di_build', 'di_choices', "readings.map(function (r, i) { var own = String(r.label + ' ' + r.label_es).toLowerCase().split(/\\s+/).filter(function (w) { return w.length > 3 && !readings.some(function (o, j) { return j !== i && String(o.label + ' ' + o.label_es).toLowerCase().split(/\\s+/).indexOf(w) > -1; }); }); return { key: 'r' + i, phrases: [di_keys[i], r.label, r.label_es].concat(own) }; })"),
397
397
  SET('di_said', 'di_value', "readings[0].pii ? '' : String(readings[0].value)"),
398
398
  SET('di_question', 'di_q', "(di_value ? 'Is ' + di_value + ' your ' : 'Is that your ') + readings.map(function (r) { return r.label; }).join(' or your ') + '? ' + readings.map(function (r, i) { return (cargo.voice ? 'Press ' + di_keys[i] + ' or say ' : 'Say ') + r.label.toUpperCase(); }).join(', ') + '.'"),
399
399
  SET('di_question_es', 'di_q_es', "(di_value ? '¿' + di_value + ' es su ' : '¿Eso es su ') + readings.map(function (r) { return r.label_es; }).join(' o su ') + '? ' + readings.map(function (r, i) { return (cargo.voice ? 'Presione ' + di_keys[i] + ' o diga ' : 'Diga ') + r.label_es.toUpperCase(); }).join(', ') + '.'"),
@@ -420,17 +420,17 @@ const disambiguate = {
420
420
  const confirmForm = {
421
421
  id: 'confirm-form', name: 'ConfirmForm', version: '1.0.0', scope: 'isolated',
422
422
  description: "Worker: ask a form's confirmation (exact YES / NO; keys 1 and 2). A correction instead ('no, make it $40') is read against the form chain and stored, and the result is 'changed' so the form runs again; an unclear short answer is asked again, a long unrelated one is DISPATCHed. Result: cargo.formConfirm[form] = 'yes' | 'no' | 'changed'. Params: form, question(_es), exit_context(_es).",
423
- parameters: ['form', 'question', 'question_es', 'exit_context', 'exit_context_es', 'words', 'interrupts', 'no_keys', 'clarifications'].map((n) => ({ name: n, type: ['words', 'interrupts', 'no_keys', 'clarifications'].includes(n) ? 'array' : 'string', description: n })),
424
- variables: vars({ cf_presets: FIELD_PRESETS, cf_chain: [], cf_m: null, cf_current: null, cf_result: '', cf_prompt: '', cf_prompt_es: '', cf_words: 0, cf_tries: 0, words: [], clarifications: [], no_keys: ['2'], interrupts: [], cf_choices: [], cf_event: '', cf_amount: false, cf_questions: [], cf_provides: null, cf_skip_gate: '' }),
423
+ parameters: ['form', 'question', 'question_es', 'exit_context', 'exit_context_es', 'phrases', 'words', 'interrupts', 'no_keys', 'clarifications'].map((n) => ({ name: n, type: ['phrases', 'words', 'interrupts', 'no_keys', 'clarifications'].includes(n) ? 'array' : 'string', description: n })),
424
+ variables: vars({ cf_presets: FIELD_PRESETS, cf_chain: [], cf_m: null, cf_current: null, cf_result: '', cf_prompt: '', cf_prompt_es: '', cf_words: 0, cf_tries: 0, phrases: null, words: [], clarifications: [], no_keys: ['2'], interrupts: [], cf_choices: [], cf_event: '', cf_amount: false, cf_questions: [], cf_provides: null, cf_skip_gate: '' }),
425
425
  steps: [
426
426
  SIDE('cf_reset', "(cargo.formConfirm = cargo.formConfirm || {}, cargo.formConfirm[form] = '', true)"),
427
- SET('cf_choices', 'cf_choices', `[{key:'yes',words:['1'].concat(Array.isArray(words)?words:[]),exact:true},{key:'no',words:(Array.isArray(no_keys)?no_keys:['2']).concat(${JSON.stringify(ANSWER_WORDS.no)}),exact:true}].concat((Array.isArray(interrupts)?interrupts:[]).map(function(event){return {key:'event:'+event.key,words:event.words,exact:event.exact!==false};}))`),
427
+ SET('cf_choices', 'cf_choices', `[{key:'yes',phrases:['1'].concat(Array.isArray(phrases)?phrases:Array.isArray(words)?words:[]),exact:true},{key:'no',phrases:(Array.isArray(no_keys)?no_keys:['2']).concat(${JSON.stringify(ANSWER_WORDS.no)}),exact:true}].concat((Array.isArray(interrupts)?interrupts:[]).map(function(event){return {key:'event:'+event.key,phrases:event.phrases ?? event.words,exact:event.exact!==false};}))`),
428
428
  SET('cf_initial_chain', 'cf_chain', CHAIN_JS),
429
429
  SET('cf_amount_context', 'cf_amount', "cf_chain.some(function(input){return input.profile && input.profile.kind==='amount';})"),
430
430
  SET('cf_prompt', 'cf_prompt', "formInputPrompt(cargo,form,'__confirm',{question:question,question_es:question_es},{},'en')"),
431
431
  SET('cf_prompt_es', 'cf_prompt_es', "formInputPrompt(cargo,form,'__confirm',{question:question,question_es:question_es},{},'es')"),
432
432
  SIDE('cf_feedback_consumed', "consumeFormFeedback(cargo,form,'__confirm')"),
433
- FLOW('cf_ask', 'ask-choice', 'call', { amount: '{{cf_amount}}', question: '{{cf_prompt}}', question_es: '{{cf_prompt_es}}', choices: '{{cf_choices}}', accept_other: true, reask_long: true, digits: { min: 1, max: 1 }, exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
433
+ FLOW('cf_ask', 'ask-choice', 'call', { form_context: { form: '{{form}}', current: '__confirm' }, amount: '{{cf_amount}}', question: '{{cf_prompt}}', question_es: '{{cf_prompt_es}}', choices: '{{cf_choices}}', accept_other: true, reask_long: true, digits: { min: 1, max: 1 }, exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
434
434
  SET('cf_event', 'cf_event', "(Array.isArray(interrupts)?interrupts:[]).filter(function(event){return cargo.choice==='event:'+event.key;}).map(function(event){return event.flow;})[0] || ''"),
435
435
  WHEN('cf_interrupt', 'cf_event', FLOW('cf_event_flow', '{{cf_event}}', 'reboot', { form: '{{form}}', event: '{{cargo.choice}}', text: '{{cargo.choiceText}}' })),
436
436
  SET('cf_build_chain', 'cf_chain', CHAIN_JS),
@@ -439,7 +439,7 @@ const confirmForm = {
439
439
  SET('cf_provider_catalog', 'cf_provides', 'cargo.forms[form].providers'),
440
440
  SET('cf_gate_policy', 'cf_skip_gate', "!cf_provides || !cf_provides.gate || [].concat(cf_provides.gate.verified || []).every(function(p){return !!formPath({cargo:cargo},p);}) ? 'true' : ''"),
441
441
  SET('cf_current', 'cf_current', "cargo.forms[form].proposalPrompt ? {form:cargo.forms[form].parent,name:cargo.forms[form].proposalPrompt.input} : {form:form,name:''}"),
442
- SET('cf_match', 'cf_m', "cargo.choice === 'yes' || cargo.choice === 'no' && pickChoice(cargo.choiceText, [{key:'no',words:Array.isArray(no_keys)?no_keys:['2'],exact:true}], false) === 'no' ? { hits: [], ambiguous: [], questions:[] } : readFormAnswer(cargo.choiceText, cf_chain, cf_current, '',cf_questions)"),
442
+ SET('cf_match', 'cf_m', "cargo.choice === 'yes' || cargo.choice === 'no' && pickChoice(cargo.choiceText, [{key:'no',phrases:Array.isArray(no_keys)?no_keys:['2'],exact:true}], false) === 'no' ? { hits: [], ambiguous: [], questions:[] } : readFormAnswer(cargo.choiceText, cf_chain, cf_current, '',cf_questions)"),
443
443
  SET('cf_enrich', 'cf_m', "(function(m){m.hits=m.hits.map(function(h){return Object.assign({},h,{silent:true});});return m;})(enrichFormMatches(cf_m, cf_chain, form))"),
444
444
  SET('cf_count_words', 'cf_words', "String(cargo.choiceText || '').split(/\\s+/).filter(function (w) { return /[a-záéíóúüñ]/i.test(w); }).length"),
445
445
  WHEN('cf_question_fields', 'cf_m.questions.length > 0 && cf_m.hits.length > 0', FLOW('cf_question_accept', 'collect-input-accept', 'call', { hits: '{{cf_m.hits}}' })),
@@ -450,7 +450,7 @@ const confirmForm = {
450
450
  'condition: cf_m.ambiguous.length > 0': FLOW('cf_ambiguous', 'disambiguate-input', 'call', { readings: '{{cf_m.ambiguous}}', hits: '{{cf_m.hits}}', remaining: '{{cf_m.remaining}}' }),
451
451
  'condition: cf_m.hits.length > 0': FLOW('cf_accept', 'collect-input-accept', 'call', { hits: '{{cf_m.hits}}' }),
452
452
  "condition: cargo.choice === 'no'": SET('cf_declined', 'cf_result', "'no'"),
453
- "condition: Array.isArray(clarifications) && pickChoice(String(cargo.choiceText || '').replace(/[?¿]/g,''),[{key:'clarify',words:clarifications,exact:true}],false)==='clarify'": SET('cf_clarification', 'cf_result', "'clarification'"),
453
+ "condition: Array.isArray(clarifications) && pickChoice(String(cargo.choiceText || '').replace(/[?¿]/g,''),[{key:'clarify',phrases:clarifications,exact:true}],false)==='clarify'": SET('cf_clarification', 'cf_result', "'clarification'"),
454
454
  'condition: cf_words >= 3 || cf_amount && cf_words > 0': yieldDispatch('cf_elsewhere', 'form', "'confirmation_not_matched'"),
455
455
  default: SET('cf_unclear', 'cf_result', "'unclear'")
456
456
  } },
@@ -637,23 +637,23 @@ const provideQueuedData = {
637
637
  };
638
638
  // the menu's choices, built where the expression can see pd_menu (FLOW parameters are paths only)
639
639
  provideData.variables.pd_menu_choices = { type: 'array', value: [] };
640
- provideData.steps.splice(provideData.steps.findIndex((s) => s.id === 'pd_menu_q'), 0, SET('pd_menu_build', 'pd_menu_choices', "pd_menu.map(function (m, i) { return { key: m.key, words: [pd_mkeys[i], m.label || m.key, m.label_es || ''].filter(Boolean) }; })"));
640
+ provideData.steps.splice(provideData.steps.findIndex((s) => s.id === 'pd_menu_q'), 0, SET('pd_menu_build', 'pd_menu_choices', "pd_menu.map(function (m, i) { return { key: m.key, phrases: [pd_mkeys[i], m.label || m.key, m.label_es || ''].filter(Boolean) }; })"));
641
641
  // provider-menu: what next, after an answer — the catalog's actions, another fact, or done (owner MENU-1016 shape)
642
642
  const providerMenu = {
643
643
  id: 'provider-menu', name: 'ProviderMenu', version: '1.0.0', scope: 'isolated',
644
- description: "Worker: after a provider answered, offer its menu (provides.menu: question(_voice)(_es) with {verb} / {name}; choices [{ key, words, flow, exact, set }]; done { words, say(_es) }). A fact or set named by its words is answered and the menu comes back; an action runs its flow (replace) after setting its `set` cargo fields; done says goodbye. Other words: DISPATCH. No words: asked once more, then 'anything else?'. Params: provides, retry.",
644
+ description: "Worker: after a provider answered, offer its menu (provides.menu: question(_voice)(_es) with {verb} / {name}; choices [{ key, phrases, flow, exact, set }]; done { phrases, say(_es) }). A fact or set named by its words is answered and the menu comes back; an action runs its flow (replace) after setting its `set` cargo fields; done says goodbye. Other phrases: DISPATCH. No phrases: asked once more, then 'anything else?'. Params: provides, retry.",
645
645
  parameters: [{ name: 'provides', type: 'object', description: 'The provider catalog' }, { name: 'retry', type: 'string', description: "'1' on the re-ask" }],
646
646
  variables: vars({ retry: '', pm_q: '', pm_q_es: '', pm_choices: [], pm_key: '', pm_keys: [], pm_close: false, pm_flow: '', pm_bye: '', pm_bye_es: '', pm_who: '', pm_sorry: '', pm_sorry_es: '' }),
647
647
  steps: [
648
648
  SET('pm_name', 'pm_who', NAME_JS),
649
649
  SET('pm_question', 'pm_q', `(function () { ${RENDER_JS} var m = provides.menu; var t = cargo.voice && m.question_voice ? m.question_voice : m.question; return (retry === '1' ? "Sorry, I didn't catch that. " : '') + fill(t, {}, null, 'en', { name: pm_who, verb: cargo.verb || (cargo.voice ? 'say' : 'type') }); })()`),
650
650
  SET('pm_question_es', 'pm_q_es', `(function () { ${RENDER_JS} var m = provides.menu; var t = cargo.voice && (m.question_voice_es || m.question_voice) ? (m.question_voice_es || m.question_voice) : (m.question_es || m.question); return (retry === '1' ? 'Disculpe, no le entendí. ' : '') + fill(t, {}, null, 'es', { name: pm_who, verb: cargo.verb_es || (cargo.voice ? 'diga' : 'escriba') }); })()`),
651
- SET('pm_build', 'pm_choices', "provides.facts.concat(provides.sets || []).filter(function (f) { return Array.isArray(f.words) && f.words.length; }).map(function (f) { return { key: 'fact:' + f.key, words: f.words }; }).concat((provides.menu.choices || []).map(function (c) { return { key: 'act:' + c.key, words: c.words, exact: c.exact === true }; })).concat(provides.menu.done ? [{ key: 'done', words: provides.menu.done.words, exact: true }] : [])"),
651
+ SET('pm_build', 'pm_choices', "provides.facts.concat(provides.sets || []).filter(function (f) { return Array.isArray(f.phrases ?? f.words) && (f.phrases ?? f.words).length; }).map(function (f) { return { key: 'fact:' + f.key, phrases: f.phrases ?? f.words }; }).concat((provides.menu.choices || []).map(function (c) { return { key: 'act:' + c.key, phrases: c.phrases ?? c.words, exact: c.exact === true }; })).concat(provides.menu.done ? [{ key: 'done', phrases: provides.menu.done.phrases ?? provides.menu.done.words, exact: true }] : [])"),
652
652
  FLOW('pm_ask', 'ask-choice', 'call', { question: '{{pm_q}}', question_es: '{{pm_q_es}}', choices: '{{pm_choices}}', accept_other: true, digits: { min: 1, max: 1 }, exit_context: '{{provides.subject}}', exit_context_es: '{{provides.subject_es}}' }),
653
653
  // A declared terminal phrase (for example "no thanks") may also fit a shorter action
654
654
  // after courtesy stripping ("no"). Resolve only that overlap; fact ownership and the
655
655
  // existing reserved done fallback retain their normal behavior.
656
- SET('pm_take', 'pm_key', "(function(){var key=String(cargo.choice || '');if(key.indexOf('fact:')===0)return pickProviderQuestion(cargo.choiceText,pm_choices.filter(function(c){return c.key.indexOf('fact:')===0;}));if(key.indexOf('act:')===0 && provides.menu.done && pickChoice(cargo.choiceText,[{key:'terminal:done',words:provides.menu.done.words,exact:true}],true)==='terminal:done')return 'done';return key;})()"),
656
+ SET('pm_take', 'pm_key', "(function(){var key=String(cargo.choice || '');if(key.indexOf('fact:')===0)return pickProviderQuestion(cargo.choiceText,pm_choices.filter(function(c){return c.key.indexOf('fact:')===0;}));if(key.indexOf('act:')===0 && provides.menu.done && pickChoice(cargo.choiceText,[{key:'terminal:done',phrases:provides.menu.done.phrases ?? provides.menu.done.words,exact:true}],true)==='terminal:done')return 'done';return key;})()"),
657
657
  SET('pm_fact_keys', 'pm_keys', "pm_key.indexOf('fact:') === 0 ? (function (k) { var s = (provides.sets || []).filter(function (x) { return x.key === k; })[0]; return s ? s.facts.slice() : [k]; })(pm_key.slice(5)) : []"),
658
658
  SET('pm_closing', 'pm_close', "pm_keys.length > 0 && pm_keys.every(function (key) { var fact = provides.facts.find(function (f) { return f.key === key; }); return !!fact && fact.close === true; })"),
659
659
  SET('pm_action_flow', 'pm_flow', "pm_key.indexOf('act:') === 0 ? (function (c) { if (c && c.set) { Object.keys(c.set).forEach(function (k) { cargo[k] = c.set[k]; }); } else { /* nothing to set */ } return c ? c.flow : ''; })((provides.menu.choices || []).filter(function (x) { return 'act:' + x.key === pm_key; })[0]) : ''"),
@@ -96,7 +96,7 @@ const contact = worker('get-cell-or-email', 'GetCellOrEmail', 'Identify a suppli
96
96
  set('identity_contact_allowed', 'contact_allowed', "!!cargo.callerId && !callerIsInternational(cargo) && !cargo.callerDeclined && contact_options.caller_on_file !== 'no'"),
97
97
  set('identity_contact_prefill', 'contact_prefill', "String(acct_number || cell_number || email || (!contact_partial && contact_allowed && contact_options.caller_on_file === 'yes' ? cargo.callerId : ''))"),
98
98
  effect('identity_contact_preselected', "(acct_number || cell_number || email ? true : (cargo.callerPreselected=!!(contact_prefill && contact_options.caller_on_file === 'yes')),true)"),
99
- set('identity_contact_profiles', 'contact_profiles', "contact_profiles_base.map(function (field) {return field.name === 'account' ? Object.assign({},field,{profile:{kind:'identifier',pattern:contact_options.account_pattern || '(?!)'}}) : field;}).concat(contact_allowed ? [{name:'caller_decision',label:'caller ID choice',label_es:'opción del identificador de llamadas',profile:{kind:'choice',choices:[{key:'yes',words:['1','yes','si','sí'],exact:true},{key:'no',words:['no','nope','nah'],exact:true}]}}] : [])"),
99
+ set('identity_contact_profiles', 'contact_profiles', "contact_profiles_base.map(function (field) {return field.name === 'account' ? Object.assign({},field,{profile:{kind:'identifier',pattern:contact_options.account_pattern || '(?!)'}}) : field;}).concat(contact_allowed ? [{name:'caller_decision',label:'caller ID choice',label_es:'opción del identificador de llamadas',profile:{kind:'choice',choices:[{key:'yes',phrases:['1','yes','si','sí'],exact:true},{key:'no',phrases:['no','nope','nah'],exact:true}]}}] : [])"),
100
100
  set('identity_contact_keypad', 'contact_keypad', "(function () {var shapes=[{first:'23456789',lengths:[10]},{first:'1',lengths:[11]}].concat(contact_options.account_shape || []);if(contact_partial){var left=[];(contact_options.account_shape || []).forEach(function(s){(s.lengths || []).forEach(function(n){var rest=n-String(cargo.gcePartial).length;if(rest>0 && left.indexOf(rest)<0)left.push(rest);});});return {min:1,max:12,autoSubmitMs:3000,complete:[{first:'0123456789',lengths:left.sort(function(a,b){return a-b;})}]};}return {min:7,max:12,autoSubmitMs:3000,autoSubmitChars:contact_allowed?['1']:[],complete:shapes};})()"),
101
101
  set('identity_contact_question', 'contact_question', expression(contactPrompt, 'cargo', 'contact_options', 'contact_allowed', 'contact_partial')),
102
102
  set('identity_contact_question_es', 'contact_question_es', expression(contactPrompt, 'cargo', 'contact_options', 'contact_allowed', 'contact_partial', 'true')),
@@ -196,7 +196,7 @@ function otpPhoneUnavailable(value) {
196
196
  return /\b(?:no longer|cannot|can't|dont|don't|do not)\s+(?:have(?:\s+access\s+to)?|access|use)\b[^.!?]{0,70}\b(?:phone|number|mobile|cellphone)\b/.test(text)
197
197
  || /\b(?:ya\s+no|no)\s+(?:tengo|puedo\s+(?:usar|acceder))\b[^.!?]{0,70}\b(?:telefono|numero|celular|movil)\b/.test(text);
198
198
  }
199
- const validateCode = worker('validate-otp-code', 'ValidateOtpCode', 'Validate a challenge response with explicit bounded retries, alternate-contact handling and tenant callbacks.', { variables: vars({ otp_words: OTP_WORDS, no_code_given: false, wants_other_account: false, other_account_given: false, otp_validation_result: false, whatsapp_invite_sent: false, invite_text: '', otp_cancel: 'contact-support', answer_key: '', answer_value: '' }), contract: { role: 'gate', summary: 'Validate the active one-time challenge', tools: ['validate-otp', 'send-whatsapp-invite'], result: { path: 'cargo.otpVerified', type: 'boolean' } }, steps: [
199
+ const validateCode = worker('validate-otp-code', 'ValidateOtpCode', 'Validate a challenge response with explicit bounded retries, alternate-contact handling and tenant callbacks.', { variables: vars({ otp_phrases: OTP_WORDS, no_code_given: false, wants_other_account: false, other_account_given: false, otp_validation_result: false, whatsapp_invite_sent: false, invite_text: '', otp_cancel: 'contact-support', answer_key: '', answer_value: '' }), contract: { role: 'gate', summary: 'Validate the active one-time challenge', tools: ['validate-otp', 'send-whatsapp-invite'], result: { path: 'cargo.otpVerified', type: 'boolean' } }, steps: [
200
200
  set('otp_cancel', 'otp_cancel', "cargo.authCancelFlow || 'contact-support'"),
201
201
  set('otp_reset_no_code', 'no_code_given', 'false'), set('otp_reset_invite', 'whatsapp_invite_sent', 'false'), set('otp_reset_callback', 'answer_key', "''"),
202
202
  when('otp_tenant_code', 'cargo.authOptions && cargo.authOptions.code_validator && normalized_otp_code.length !== 6 && /[0-9]/.test(user_choice)', call('otp_tenant_code_call', '{{cargo.authOptions.code_validator}}', { answer: '{{user_choice}}' })),
@@ -264,15 +264,15 @@ export function emailReadback(address, voice, es = false) {
264
264
  said = said.split('').join(' ').replace(/ @ /, es ? ' arroba ' : ' at ').replace(/ \. /g, es ? ' punto ' : ' dot ').replace(/ _ /g, es ? ' guion bajo ' : ' underscore ').replace(/ - /g, es ? ' guion ' : ' dash ');
265
265
  return (es ? 'Tengo ' : 'I have ') + said + (es ? '. ¿Es correcto? ' : '. Is that right? ') + (es ? voice ? 'Presione 1 o diga' : 'Escriba' : voice ? 'Press 1 or say' : 'Type') + (es ? ' SÍ, o ' : ' YES, or ') + (es ? voice ? 'presione 2 o diga' : 'escriba' : voice ? 'press 2 or say' : 'type') + (es ? ' NO.' : ' NO.');
266
266
  }
267
- const email = worker('ask-email', 'AskEmail', 'Collect an email through shared FORM matching, retaining field-specific spelling and readback behavior.', { scope: 'isolated', parameters: [param('question', 'English email question'), param('question_es', 'Spanish email question'), param('on_file', 'Known email offered by OK'), param('attempt', 'Retry attempt'), param('why', 'invalid, retry or more'), param('confirm', 'Read back a caller-supplied known address'), param('parent_form', 'Owning task FORM instance'), param('email_state', 'Internal field protocol state', 'object')], variables: vars({ question: '', question_es: '', on_file: '', attempt: '', why: '', confirm: '', parent_form: '', email_state: null, email_question: '', email_question_es: '', email_raw: '', email_found: '', email_spelling: false, email_new: false, email_choice: '', email_readback: '', email_readback_es: '', email_choices: EMAIL_CHOICES, email_profiles_base: [{ name: 'email_address', label: 'email address', label_es: 'correo electrónico', profile: { kind: 'email' } }, raw], email_profiles: [], email_confirm_profiles: [{ name: 'decision', label: 'email confirmation', label_es: 'confirmación de correo', profile: { kind: 'choice', choices: [{ key: 'no', words: ['2', 'no', 'wrong', 'incorrect', 'incorrecto'] }, { key: 'yes', words: ['1', 'yes', 'sí', 'si', 'correct', 'correcto'] }] } }, raw] }), contract: { role: 'collector', summary: 'Email field spelling and readback service', result: { path: 'cargo.email', type: 'string' } }, steps: [
267
+ const email = worker('ask-email', 'AskEmail', 'Collect an email through shared FORM matching, retaining field-specific spelling and readback behavior.', { scope: 'isolated', parameters: [param('question', 'English email question'), param('question_es', 'Spanish email question'), param('on_file', 'Known email offered by OK'), param('attempt', 'Retry attempt'), param('why', 'invalid, retry or more'), param('confirm', 'Read back a caller-supplied known address'), param('parent_form', 'Owning task FORM instance'), param('email_state', 'Internal field protocol state', 'object')], variables: vars({ question: '', question_es: '', on_file: '', attempt: '', why: '', confirm: '', parent_form: '', email_state: null, email_question: '', email_question_es: '', email_raw: '', email_found: '', email_spelling: false, email_new: false, email_choice: '', email_readback: '', email_readback_es: '', email_choices: EMAIL_CHOICES, email_profiles_base: [{ name: 'email_address', label: 'email address', label_es: 'correo electrónico', profile: { kind: 'email' } }, raw], email_profiles: [], email_confirm_profiles: [{ name: 'decision', label: 'email confirmation', label_es: 'confirmación de correo', profile: { kind: 'choice', choices: [{ key: 'no', phrases: ['2', 'no', 'wrong', 'incorrect', 'incorrecto'] }, { key: 'yes', phrases: ['1', 'yes', 'sí', 'si', 'correct', 'correcto'] }] } }, raw] }), contract: { role: 'collector', summary: 'Email field spelling and readback service', result: { path: 'cargo.email', type: 'string' } }, steps: [
268
268
  set('email_protocol', 'email_state', "email_state || {question:question,question_es:question_es || question,on_file:on_file,confirm:confirm === true || confirm === 'true',attempt:Number(attempt || 0),why:why,draft:why === 'more'?String(cargo.emailDraft || ''):'',parent_form:parent_form}"),
269
- set('email_profiles', 'email_profiles', "email_profiles_base.concat(email_state.on_file ? [{name:'known_email_choice',label:'email destination choice',label_es:'opción de destino del correo',profile:{kind:'choice',choices:[{key:'ok',words:email_choices.ok},{key:'another',words:email_choices.another}]}}] : [])"),
269
+ set('email_profiles', 'email_profiles', "email_profiles_base.concat(email_state.on_file ? [{name:'known_email_choice',label:'email destination choice',label_es:'opción de destino del correo',profile:{kind:'choice',choices:[{key:'ok',phrases:email_choices.ok},{key:'another',phrases:email_choices.another}]}}] : [])"),
270
270
  set('email_question', 'email_question', "email_state.why === 'more' ? 'Got it. Go on.' : (email_state.attempt>0 ? email_state.why === 'retry' ? \"Okay, let's try again. \" : \"That doesn't look like an email address. \" : '')+email_state.question"),
271
271
  set('email_question_es', 'email_question_es', "email_state.why === 'more' ? 'Entendido. Continúe.' : (email_state.attempt>0 ? email_state.why === 'retry' ? 'De acuerdo, intentemos de nuevo. ' : 'Eso no parece un correo electrónico. ' : '')+email_state.question_es"),
272
272
  call('email_collect', 'collect-service-answer', { profiles: '{{email_profiles}}', question: '{{email_question}}', question_es: '{{email_question_es}}', keypad: { min: 1, max: 1 }, parent_form: '{{email_state.parent_form}}', context: 'email', context_es: 'correo' }),
273
273
  set('email_raw', 'email_raw', 'String(cargo.serviceAnswer.raw || "")'),
274
274
  cases('email_command', { "condition: isAgentRequest(email_raw)": call('email_agent', 'live-agent-requested', undefined, 'reboot'), "condition: isAnswer(email_raw,'exit')": call('email_exit', 'contact-support', { support_context: 'email', support_context_es: 'correo' }, 'reboot'), default: effect('email_is_answer', 'true') }),
275
- set('email_choice', 'email_choice', "pickChoice(email_raw,[{key:'ok',words:email_choices.ok},{key:'another',words:email_choices.another}],false)"),
275
+ set('email_choice', 'email_choice', "pickChoice(email_raw,[{key:'ok',phrases:email_choices.ok},{key:'another',phrases:email_choices.another}],false)"),
276
276
  when('email_other_request_clear', "!email_choice && !readEmail(email_raw) && isOtherRequest(email_raw,'email')", effect('email_other_request_draft', "(email_state.draft='',cargo.emailDraft='',cargo.email='',true)")),
277
277
  when('email_other_request', "!email_choice && !readEmail(email_raw) && isOtherRequest(email_raw,'email')", { id: 'email_dispatch_request', type: 'DISPATCH' }),
278
278
  set('email_parse', 'email_found', "(email_state.draft ? readEmail(email_state.draft+' '+email_raw) : '') || readEmail(email_raw) || (email_choice === 'ok' && email_state.on_file ? String(email_state.on_file).toLowerCase() : '')"),
@@ -282,9 +282,9 @@ const email = worker('ask-email', 'AskEmail', 'Collect an email through shared F
282
282
  set('email_new', 'email_new', '!!email_found && (email_state.confirm || String(email_state.on_file || "").toLowerCase() !== email_found)'),
283
283
  set('email_readback', 'email_readback', expression(emailReadback, 'email_found', 'cargo.voice')), set('email_readback_es', 'email_readback_es', expression(emailReadback, 'email_found', 'cargo.voice', 'true')),
284
284
  when('email_verify_new', 'email_new', call('email_readback_collect', 'collect-service-answer', { profiles: '{{email_confirm_profiles}}', question: '{{email_readback}}', question_es: '{{email_readback_es}}', keypad: { min: 1, max: 1 }, parent_form: '{{email_state.parent_form}}', context: 'email', context_es: 'correo' })),
285
- when('email_readback_other_clear', "email_new && isOtherRequest(cargo.serviceAnswer.raw,'email') && !pickChoice(cargo.serviceAnswer.raw,[{key:'yes',words:['1','yes','sí','si','correct','correcto']},{key:'no',words:['2','no','wrong','incorrect','incorrecto']}],false)", effect('email_readback_other_draft', "(email_state.draft='',cargo.emailDraft='',cargo.email='',true)")),
286
- when('email_readback_other', "email_new && isOtherRequest(cargo.serviceAnswer.raw,'email') && !pickChoice(cargo.serviceAnswer.raw,[{key:'yes',words:['1','yes','sí','si','correct','correcto']},{key:'no',words:['2','no','wrong','incorrect','incorrecto']}],false)", { id: 'email_readback_dispatch', type: 'DISPATCH' }),
287
- when('email_readback_wrong', "email_new && pickChoice(cargo.serviceAnswer.raw,[{key:'no',words:['2','no','wrong','incorrect','incorrecto']},{key:'yes',words:['1','yes','sí','si','correct','correcto']}],false) !== 'yes'", set('email_rejected', 'email_found', "''")),
285
+ when('email_readback_other_clear', "email_new && isOtherRequest(cargo.serviceAnswer.raw,'email') && !pickChoice(cargo.serviceAnswer.raw,[{key:'yes',phrases:['1','yes','sí','si','correct','correcto']},{key:'no',phrases:['2','no','wrong','incorrect','incorrecto']}],false)", effect('email_readback_other_draft', "(email_state.draft='',cargo.emailDraft='',cargo.email='',true)")),
286
+ when('email_readback_other', "email_new && isOtherRequest(cargo.serviceAnswer.raw,'email') && !pickChoice(cargo.serviceAnswer.raw,[{key:'yes',phrases:['1','yes','sí','si','correct','correcto']},{key:'no',phrases:['2','no','wrong','incorrect','incorrecto']}],false)", { id: 'email_readback_dispatch', type: 'DISPATCH' }),
287
+ when('email_readback_wrong', "email_new && pickChoice(cargo.serviceAnswer.raw,[{key:'no',phrases:['2','no','wrong','incorrect','incorrecto']},{key:'yes',phrases:['1','yes','sí','si','correct','correcto']}],false) !== 'yes'", set('email_rejected', 'email_found', "''")),
288
288
  when('email_got_address', '!!email_found', effect('email_store', "(cargo.email=email_found,cargo.emailDraft='',true)")), when('email_return_address', '!!email_found', end('email_complete')),
289
289
  when('email_other_address', "email_choice === 'another' && !!email_state.on_file", effect('email_change_offer', "(email_state.question='What email address should I send it to?',email_state.question_es='¿A qué correo electrónico se lo envío?',email_state.on_file='',email_state.confirm=false,email_state.attempt=-1,true)")),
290
290
  effect('email_retry_state', "(email_state.attempt+=1,email_state.why=email_new?'retry':'invalid',email_state.draft='',cargo.emailDraft='',true)"),
@@ -2,9 +2,11 @@ export const FLOWS: any[];
2
2
  export { FLOWS as IDENTITY_FLOWS } from "./identity-flows.js";
3
3
  export { compileFormPrompts } from "./prompt-compiler.js";
4
4
  export { explainSession } from "./inspection.js";
5
+ export { inheritFlowDeclaration } from "./declaration-capture.js";
5
6
  export { withSafetyRevision, CONTINUATION_SAFETY_REQUIREMENT } from "./continuation-safety.js";
6
7
  export { FIELD_PRESETS, formFlow, declinedFlow, textValue } from "./flows.js";
7
8
  export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from "./contracts.js";
8
9
  export { addressDraft, zipLocation, streetLocation, resolvedAddress } from "../helpers/address.js";
9
10
  export { Form, Provider, Performer, Worker, compileExpression } from "./authoring.js";
11
+ export { compileFlowDeclarations, serializeFlowDeclaration, captureOriginalDeclaration } from "./declarations.js";
10
12
  //# sourceMappingURL=index.d.ts.map
@@ -12,3 +12,5 @@ export { compileFormPrompts } from './prompt-compiler.js';
12
12
  export { addressDraft, zipLocation, streetLocation, resolvedAddress } from '../helpers/address.js';
13
13
  export { explainSession } from './inspection.js';
14
14
  export { Form, Provider, Performer, Worker, compileExpression } from './authoring.js';
15
+ export { compileFlowDeclarations, serializeFlowDeclaration, captureOriginalDeclaration } from './declarations.js';
16
+ export { inheritFlowDeclaration } from './declaration-capture.js';
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-compiler.d.ts","sourceRoot":"","sources":["../../src/forms/prompt-compiler.js"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,sDAuBC"}
1
+ {"version":3,"file":"prompt-compiler.d.ts","sourceRoot":"","sources":["../../src/forms/prompt-compiler.js"],"names":[],"mappings":"AACA,yFAAyF;AACzF,sDAyBC"}
@@ -1,13 +1,16 @@
1
+ import { inheritFlowDeclaration } from './declaration-capture.js';
1
2
  /** Compile contextual field prompts into workers; source declarations stay immutable. */
2
3
  export function compileFormPrompts(forms) {
3
4
  const workers = [];
4
5
  const flows = forms.map(source => {
5
- const flow = structuredClone(source);
6
+ const flow = inheritFlowDeclaration(source, structuredClone(source));
6
7
  const visit = input => {
7
8
  if (input.any_of) {
8
9
  input.any_of.forEach(visit);
9
10
  return;
10
11
  }
12
+ if (input.question_from)
13
+ return;
11
14
  if (!String(input.question || '').includes('{{') && !String(input.question_es || '').includes('{{'))
12
15
  return;
13
16
  const id = flow.id + '-' + input.name + '-question';
@@ -18,6 +21,7 @@ export function compileFormPrompts(forms) {
18
21
  set('en', 'en', literal(input.question || '')), set('es', 'es', literal(input.question_es || input.question || '')),
19
22
  set('store', 'noop', `(cargo.forms[form].data=Object.assign({},cargo.forms[form].data,{${JSON.stringify(input.name + '_question')}:en,${JSON.stringify(input.name + '_question_es')}:es}),true)`)];
20
23
  workers.push({ id, name: flow.name + input.name + 'Question', version: '1.0.0', scope: 'isolated', description: 'Render the declared field question in its owning form context.',
24
+ ...(flow.metadata?.declaration ? { metadata: { declaration: { ...flow.metadata.declaration } } } : {}),
21
25
  parameters: [{ name: 'form', type: 'string' }, { name: 'input', type: 'string' }],
22
26
  variables: { data: { type: 'object', value: null }, en: { type: 'string', value: '' }, es: { type: 'string', value: '' }, contract: { type: 'object', value: { version: 1, role: 'worker', summary: 'Render a contextual form prompt', parametersFrom: 'parameters', result: { path: 'cargo.forms[form].data', type: 'object' } } } }, steps });
23
27
  input.prepare = id;
@@ -35,7 +35,7 @@ export function numericAmountReading(input: any): {
35
35
  };
36
36
  /**
37
37
  * ask-choice's matcher: the key of the choice the answer picks, '__agent', '__exit', or '' (no choice).
38
- * choices: [{ key, words, negative?, neutral?, exact? }]. A key (digit, * or #) and a YES word pick a choice only as the whole
38
+ * choices: [{ key, phrases, negative?, neutral?, exact? }]. A key (digit, * or #) and a YES word pick a choice only as the whole
39
39
  * answer, courtesy aside (onlyAffirmative); an `exact` choice (one that charges or cancels) treats ALL its words that way. A choice keyed 'yes' also takes ANSWER_WORDS.yes (CONFIRM_WORDS when `exact`) and, when not `exact`, a bare thanks (THANKS), and the NO-type
40
40
  * choice (key no / decline / done / cancel, or negative: true) also takes ANSWER_WORDS.no, so callers list only their
41
41
  * extras. A word after a negation in its clause is negated: it picks the NO-type choice; a `neutral` choice still
@@ -346,7 +346,7 @@ function spokenKeys(b) {
346
346
  }
347
347
  /**
348
348
  * ask-choice's matcher: the key of the choice the answer picks, '__agent', '__exit', or '' (no choice).
349
- * choices: [{ key, words, negative?, neutral?, exact? }]. A key (digit, * or #) and a YES word pick a choice only as the whole
349
+ * choices: [{ key, phrases, negative?, neutral?, exact? }]. A key (digit, * or #) and a YES word pick a choice only as the whole
350
350
  * answer, courtesy aside (onlyAffirmative); an `exact` choice (one that charges or cancels) treats ALL its words that way. A choice keyed 'yes' also takes ANSWER_WORDS.yes (CONFIRM_WORDS when `exact`) and, when not `exact`, a bare thanks (THANKS), and the NO-type
351
351
  * choice (key no / decline / done / cancel, or negative: true) also takes ANSWER_WORDS.no, so callers list only their
352
352
  * extras. A word after a negation in its clause is negated: it picks the NO-type choice; a `neutral` choice still
@@ -397,7 +397,7 @@ export function pickChoice(answer, choices, acceptOther) {
397
397
  let blocked = false;
398
398
  let found = '';
399
399
  for (const c of cs) {
400
- const own = Array.isArray(c.words) ? c.words : [];
400
+ const own = Array.isArray(c.phrases) ? c.phrases : Array.isArray(c.words) ? c.words : [];
401
401
  const all = c.key === 'yes' ? [...own, ...(c.exact === true ? CONFIRM_WORDS : ANSWER_WORDS.yes)] : (c.key === noChoice ? [...own, ...ANSWER_WORDS.no] : own);
402
402
  // Strict words pick this choice only when they are the whole answer (onlyAffirmative): a key, a YES word, or — on an
403
403
  // `exact` choice (one that charges or cancels) — every word. The rest (named actions: LINK, RECEIPT…) match inside it.
@@ -40,7 +40,7 @@ export function completeSourceRefresh(cargo, source, now = Date.now()) {
40
40
  /** Prefer the most specific positively matched catalog phrase over a contained broad fact alias.
41
41
  * Ordinary menu actions retain their own exact-choice rules. No match returns no fact. */
42
42
  export function pickProviderQuestion(answer, questions = []) {
43
- const matches = questions.flatMap((question, index) => (question.words || []).flatMap(word => pickChoice(answer, [{ ...question, words: [word] }], false) === question.key
43
+ const matches = questions.flatMap((question, index) => (question.phrases ?? question.words ?? []).flatMap(word => pickChoice(answer, [{ ...question, phrases: [word] }], false) === question.key
44
44
  ? [{ key: question.key, length: String(word).normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim().length, index }] : []));
45
45
  matches.sort((a, b) => b.length - a.length || a.index - b.index);
46
46
  return matches[0]?.key || '';
@@ -1,3 +1,4 @@
1
+ export { compileNamedFunctions } from "./named-functions.js";
1
2
  export namespace STANDARD_FUNCTIONS {
2
3
  export { continuationSafetyProtocol };
3
4
  export { cancelFormTask };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/helpers/index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAAyC,iCAAiC;+BAI6C,wBAAwB;2CAHjE,0BAA0B;qCAA1B,0BAA0B;gCAA1B,0BAA0B;mCACsE,qBAAqB;kCAArB,qBAAqB;iCAArB,qBAAqB;qCAArB,qBAAqB;iCAArB,qBAAqB;mCAArB,qBAAqB;oCAArB,qBAAqB;6CAArB,qBAAqB;qCAC/E,wBAAwB;2CAAxB,wBAAwB;+CAAxB,wBAAwB;uCAAxB,wBAAwB;gCACrB,wBAAwB;8BAAxB,wBAAwB;gCAAxB,wBAAwB;oCAAxB,wBAAwB;wCAAxB,wBAAwB;gCAmBhB,YAAY;8BAAZ,YAAY;kCAAZ,YAAY;uCAAZ,YAAY;qCAAZ,YAAY;qCAAZ,YAAY;gCAlB3G,mBAAmB;8BAiBrB,qBAAqB;6BAEkG,aAAa;8BAAb,aAAa;yBAAb,aAAa;+BAAb,aAAa;+BAAb,aAAa;kCAAb,aAAa;+BAAb,aAAa;+BAAb,aAAa;2BAAb,aAAa;0BACT,cAAc;0BAAd,cAAc;uCAAd,cAAc;+BAAd,cAAc;sBAAd,cAAc;0BAAd,cAAc;iCAAd,cAAc;gCAAd,cAAc;sCAAd,cAAc;wCAC/H,cAAc;6BACP,cAAc;wBAAd,cAAc;wBAAd,cAAc;4BACjC,iBAAiB;+BACd,uBAAuB;mCACC,kBAAkB;mCAAlB,kBAAkB;qCAxB+I,mBAAmB;yCAAnB,mBAAmB;8BAAnB,mBAAmB;iCAAnB,mBAAmB;oCAAnB,mBAAmB;kCAAnB,mBAAmB;wCAAnB,mBAAmB;gCAAnB,mBAAmB;iCAAnB,mBAAmB;mCAAnB,mBAAmB;gCAe1I,mBAAmB;mCAAnB,mBAAmB;sCAAnB,mBAAmB;qCAAnB,mBAAmB;4BAUtD,mBAAmB;+BAAnB,mBAAmB;iCAAnB,mBAAmB;kCAC+nB,iBAAiB;iCAAjB,iBAAiB;gCAAjB,iBAAiB;8BAAjB,iBAAiB;+BAAjB,iBAAiB;iCAAjB,iBAAiB;8CAAjB,iBAAiB;sCAAjB,iBAAiB;uCAAjB,iBAAiB;iCAAjB,iBAAiB;oCAAjB,iBAAiB;kCAAjB,iBAAiB;mCAAjB,iBAAiB;oCAAjB,iBAAiB;wCAAjB,iBAAiB;sCAAjB,iBAAiB;kCAAjB,iBAAiB;sCAAjB,iBAAiB;sCAAjB,iBAAiB;sCAAjB,iBAAiB;gCAAjB,iBAAiB;6BAAjB,iBAAiB;yBAAjB,iBAAiB;gCAAjB,iBAAiB;iCAAjB,iBAAiB;oCAAjB,iBAAiB;gCAAjB,iBAAiB;kCAAjB,iBAAiB;oCAAjB,iBAAiB;8BAAjB,iBAAiB;mCAAjB,iBAAiB;qCAAjB,iBAAiB;mCAAjB,iBAAiB;oCAAjB,iBAAiB;iCAAjB,iBAAiB;kCAAjB,iBAAiB;yBAC3pB,gBAAgB;gCAAhB,gBAAgB;4BAAhB,gBAAgB;8BAAhB,gBAAgB;+BACzB,iBAAiB;8BAAjB,iBAAiB;8BAAjB,iBAAiB;4BAC7B,iBAAiB;oCAAjB,iBAAiB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/helpers/index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CACyC,iCAAiC;+BAI6C,wBAAwB;2CAHjE,0BAA0B;qCAA1B,0BAA0B;gCAA1B,0BAA0B;mCACsE,qBAAqB;kCAArB,qBAAqB;iCAArB,qBAAqB;qCAArB,qBAAqB;iCAArB,qBAAqB;mCAArB,qBAAqB;oCAArB,qBAAqB;6CAArB,qBAAqB;qCAC/E,wBAAwB;2CAAxB,wBAAwB;+CAAxB,wBAAwB;uCAAxB,wBAAwB;gCACrB,wBAAwB;8BAAxB,wBAAwB;gCAAxB,wBAAwB;oCAAxB,wBAAwB;wCAAxB,wBAAwB;gCAmBhB,YAAY;8BAAZ,YAAY;kCAAZ,YAAY;uCAAZ,YAAY;qCAAZ,YAAY;qCAAZ,YAAY;gCAlB3G,mBAAmB;8BAiBrB,qBAAqB;6BAEkG,aAAa;8BAAb,aAAa;yBAAb,aAAa;+BAAb,aAAa;+BAAb,aAAa;kCAAb,aAAa;+BAAb,aAAa;+BAAb,aAAa;2BAAb,aAAa;0BACT,cAAc;0BAAd,cAAc;uCAAd,cAAc;+BAAd,cAAc;sBAAd,cAAc;0BAAd,cAAc;iCAAd,cAAc;gCAAd,cAAc;sCAAd,cAAc;wCAC/H,cAAc;6BACP,cAAc;wBAAd,cAAc;wBAAd,cAAc;4BACjC,iBAAiB;+BACd,uBAAuB;mCACC,kBAAkB;mCAAlB,kBAAkB;qCAxB+I,mBAAmB;yCAAnB,mBAAmB;8BAAnB,mBAAmB;iCAAnB,mBAAmB;oCAAnB,mBAAmB;kCAAnB,mBAAmB;wCAAnB,mBAAmB;gCAAnB,mBAAmB;iCAAnB,mBAAmB;mCAAnB,mBAAmB;gCAe1I,mBAAmB;mCAAnB,mBAAmB;sCAAnB,mBAAmB;qCAAnB,mBAAmB;4BAUtD,mBAAmB;+BAAnB,mBAAmB;iCAAnB,mBAAmB;kCAC+nB,iBAAiB;iCAAjB,iBAAiB;gCAAjB,iBAAiB;8BAAjB,iBAAiB;+BAAjB,iBAAiB;iCAAjB,iBAAiB;8CAAjB,iBAAiB;sCAAjB,iBAAiB;uCAAjB,iBAAiB;iCAAjB,iBAAiB;oCAAjB,iBAAiB;kCAAjB,iBAAiB;mCAAjB,iBAAiB;oCAAjB,iBAAiB;wCAAjB,iBAAiB;sCAAjB,iBAAiB;kCAAjB,iBAAiB;sCAAjB,iBAAiB;sCAAjB,iBAAiB;sCAAjB,iBAAiB;gCAAjB,iBAAiB;6BAAjB,iBAAiB;yBAAjB,iBAAiB;gCAAjB,iBAAiB;iCAAjB,iBAAiB;oCAAjB,iBAAiB;gCAAjB,iBAAiB;kCAAjB,iBAAiB;oCAAjB,iBAAiB;8BAAjB,iBAAiB;mCAAjB,iBAAiB;qCAAjB,iBAAiB;mCAAjB,iBAAiB;oCAAjB,iBAAiB;iCAAjB,iBAAiB;kCAAjB,iBAAiB;yBAC3pB,gBAAgB;gCAAhB,gBAAgB;4BAAhB,gBAAgB;8BAAhB,gBAAgB;+BACzB,iBAAiB;8BAAjB,iBAAiB;8BAAjB,iBAAiB;4BAC7B,iBAAiB;oCAAjB,iBAAiB"}
@@ -1,3 +1,4 @@
1
+ export { compileNamedFunctions } from './named-functions.js';
1
2
  import { continuationSafetyProtocol } from '../forms/continuation-safety.js';
2
3
  import { contextualResponseProtocol, validateFormResponse, hasFormResponse } from './contextual-response.js';
3
4
  import { formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation } from './form-proposals.js';
@@ -94,8 +94,8 @@ export function readInputProfile(profile, answer, isCurrent = true) {
94
94
  const kind = profile && profile.kind;
95
95
  if (kind === 'choice') {
96
96
  const choices = (Array.isArray(profile.choices) ? profile.choices : []).filter(c => isCurrent || c.current_only !== true).map(c => ({ ...c,
97
- numericWords: (c.words || []).filter(word => /^\d{2,}$/.test(String(word).trim())),
98
- words: (c.words || []).concat(isCurrent ? c.keys || [] : []).filter(word => !(isAmountAnswer(raw) && /^\d+$/.test(String(word).trim())) && (isCurrent || profile.numeric_values === true || !/^[\d*#]$/.test(String(word).trim()))) }));
97
+ numericWords: (c.phrases ?? c.words ?? []).filter(word => /^\d{2,}$/.test(String(word).trim())),
98
+ phrases: (c.phrases ?? c.words ?? []).concat(isCurrent ? c.keys || [] : []).filter(word => !(isAmountAnswer(raw) && /^\d+$/.test(String(word).trim())) && (isCurrent || profile.numeric_values === true || !/^[\d*#]$/.test(String(word).trim()))) }));
99
99
  // Semantic numeric values may arrive in ASR groups ("95 52"), unlike menu keys.
100
100
  // Keep choice policy in pickChoice and source evidence in the original utterance.
101
101
  const runs = digitRuns(raw), joined = raw.replace(/\d(?:[\s.-]?\d)*/g, run => ' ' + run.replace(/\D/g, '') + ' ');
@@ -103,7 +103,7 @@ export function readInputProfile(profile, answer, isCurrent = true) {
103
103
  if (isAmountAnswer(raw))
104
104
  return [];
105
105
  const words = c.numericWords.filter(word => runs.includes(String(word).trim()));
106
- if (!words.length || pickChoice(joined, [{ ...c, words }], false) !== c.key)
106
+ if (!words.length || pickChoice(joined, [{ ...c, phrases: words }], false) !== c.key)
107
107
  return [];
108
108
  return words.flatMap(word => numberSpans(raw, String(word).trim()).filter(([a, b]) => raw.slice(a, b).replace(/\D/g, '') === String(word).trim()));
109
109
  };
@@ -112,9 +112,9 @@ export function readInputProfile(profile, answer, isCurrent = true) {
112
112
  const picked = choices.find(c => c.key === base);
113
113
  const pool = picked && negative(picked) ? [picked] : choices.filter(c => !negative(c));
114
114
  let readings = pool.filter(c => pickChoice(raw, [c], false) === c.key || numericSpans(c).length).map(c => {
115
- const words = (c.words || []).filter(w => matchesChoice(raw, [w]));
115
+ const words = (c.phrases ?? c.words ?? []).filter(w => matchesChoice(raw, [w]));
116
116
  const spans = [...choiceSpans(raw, words), ...numericSpans(c)].filter((span, index, all) => all.findIndex(other => other[0] === span[0] && other[1] === span[1]) === index);
117
- return { value: c.key, ...(isCurrent && (c.keys || []).length && !isAmountAnswer(raw) && pickChoice(raw, [{ key: c.key, words: c.keys, exact: true }], false) === c.key ? { keypad: true } : {}), spans: spans.length ? spans : [[0, raw.length]], option_label: c.label || (c.words || []).find(w => !/^\d+$/.test(w)) || c.key, option_label_es: c.label_es || c.label || c.key };
117
+ return { value: c.key, ...(isCurrent && (c.keys || []).length && !isAmountAnswer(raw) && pickChoice(raw, [{ key: c.key, phrases: c.keys, exact: true }], false) === c.key ? { keypad: true } : {}), spans: spans.length ? spans : [[0, raw.length]], option_label: c.label || (c.phrases ?? c.words ?? []).find(w => !/^\d+$/.test(w)) || c.key, option_label_es: c.label_es || c.label || c.key };
118
118
  });
119
119
  // A more specific declared phrase can cover a shorter phrase of the same field's other option.
120
120
  readings = readings.filter(r => !readings.some(other => other !== r && r.spans.every(([a, b]) => other.spans.some(([c, d]) => c <= a && d >= b && (c < a || d > b)))));
@@ -0,0 +1,5 @@
1
+ export function compileNamedFunctions(definitions: any, { approvedFunctions, label }?: {
2
+ approvedFunctions?: {} | undefined;
3
+ label?: string | undefined;
4
+ }): any;
5
+ //# sourceMappingURL=named-functions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"named-functions.d.ts","sourceRoot":"","sources":["../../src/helpers/named-functions.js"],"names":[],"mappings":"AAOA;;;QAkCC"}
@@ -0,0 +1,54 @@
1
+ /** Compile trusted, JSON-saved JavaScript helpers once for a loaded flow definition.
2
+ * Only explicit arguments and approved platform helpers enter their lexical scope.
3
+ * Runtime/session values are passed by callers; a registry never captures a session.
4
+ */
5
+ const identifier = /^[A-Za-z_$][\w$]*$/;
6
+ const forbidden = new Set(['fn', '__proto__', 'prototype', 'constructor']);
7
+ const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
8
+ export function compileNamedFunctions(definitions, { approvedFunctions = {}, label = 'flow' } = {}) {
9
+ if (definitions === undefined)
10
+ return undefined;
11
+ if (!definitions || typeof definitions !== 'object' || Array.isArray(definitions))
12
+ throw new Error(`Named functions ${label}: functions must be an object`);
13
+ const names = Object.keys(definitions);
14
+ if (!names.length)
15
+ return undefined;
16
+ const fail = message => { throw new Error(`Named functions ${label}: ${message}`); };
17
+ const validName = (name, kind) => {
18
+ if (typeof name !== 'string' || !identifier.test(name) || forbidden.has(name))
19
+ fail(`invalid ${kind} ${String(name)}`);
20
+ return name;
21
+ };
22
+ const statements = names.map(name => {
23
+ validName(name, 'function name');
24
+ const spec = definitions[name];
25
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec))
26
+ fail(`${name} must declare parameters and body`);
27
+ if (!Array.isArray(spec.parameters))
28
+ fail(`${name}.parameters must be an array`);
29
+ const parameters = spec.parameters.map(parameter => {
30
+ if (!parameter || typeof parameter !== 'object' || Array.isArray(parameter) || typeof parameter.name !== 'string' || !identifier.test(parameter.name))
31
+ fail(`${name} has an invalid parameter`);
32
+ return (parameter.rest === true ? '...' : '') + parameter.name;
33
+ });
34
+ if (new Set(parameters).size !== parameters.length)
35
+ fail(`${name} has duplicate parameters`);
36
+ if (!Array.isArray(spec.body) || spec.body.some(line => typeof line !== 'string'))
37
+ fail(`${name}.body must be an array of JavaScript lines`);
38
+ const expressionName = spec.name === undefined ? name : validName(spec.name, 'function expression name');
39
+ return `const ${name}=function ${expressionName}(${parameters.join(',')}){\n${spec.body.join('\n')}\n};`;
40
+ });
41
+ // Local declaration names shadow same-named approved helpers exactly as ordinary JS lexical bindings do.
42
+ const approvedNames = Object.keys(approvedFunctions).filter(name => identifier.test(name) && name !== 'fn' && !own(definitions, name));
43
+ let factory;
44
+ try {
45
+ factory = new Function('fn', ...approvedNames, `"use strict";\n${statements.join('\n')}\nreturn [${names.join(',')}];`);
46
+ }
47
+ catch (error) {
48
+ fail(`invalid JavaScript: ${error.message}`);
49
+ }
50
+ const namespace = Object.create(null);
51
+ const functions = factory(namespace, ...approvedNames.map(name => approvedFunctions[name]));
52
+ names.forEach((name, index) => { namespace[name] = functions[index]; });
53
+ return Object.freeze(namespace);
54
+ }
@@ -26,7 +26,7 @@ export function validateProposalData(value, seen = new Set()) {
26
26
  seen.delete(value);
27
27
  return value;
28
28
  }
29
- const confirmationKeys = ['question', 'question_es', 'binding', 'words', 'interrupts', 'no_keys', 'clarifications', 'on_declined'];
29
+ const confirmationKeys = ['question', 'question_es', 'binding', 'phrases', 'words', 'interrupts', 'no_keys', 'clarifications', 'on_declined'];
30
30
  function confirmation(value, required) {
31
31
  if (required && !string(value.question))
32
32
  fail('needs a nonempty question');
@@ -35,15 +35,15 @@ function confirmation(value, required) {
35
35
  fail(key + ' must be nonempty text');
36
36
  if (value.on_declined !== undefined && !safeName(value.on_declined))
37
37
  fail('on_declined needs a static worker id');
38
- for (const key of ['words', 'no_keys', 'clarifications'])
38
+ for (const key of ['phrases', 'words', 'no_keys', 'clarifications'])
39
39
  if (value[key] !== undefined && (!Array.isArray(value[key]) || !value[key].every(string)))
40
- fail(key + ' must be an array of nonempty words');
40
+ fail(key + ' must be an array of nonempty phrases');
41
41
  if (value.interrupts !== undefined) {
42
42
  if (!Array.isArray(value.interrupts))
43
43
  fail('interrupts must be an array');
44
44
  const keys = new Set();
45
45
  for (const event of value.interrupts) {
46
- if (!plain(event) || Object.keys(event).some(k => !['key', 'words', 'flow', 'exact'].includes(k)) || !safeName(event.key) || keys.has(event.key) || !safeName(event.flow) || !Array.isArray(event.words) || !event.words.length || !event.words.every(string) || event.exact !== undefined && typeof event.exact !== 'boolean')
46
+ if (!plain(event) || Object.keys(event).some(k => !['key', 'phrases', 'words', 'flow', 'exact'].includes(k)) || !safeName(event.key) || keys.has(event.key) || !safeName(event.flow) || !Array.isArray(event.phrases ?? event.words) || !(event.phrases ?? event.words).length || !(event.phrases ?? event.words).every(string) || event.exact !== undefined && typeof event.exact !== 'boolean')
47
47
  fail('invalid interrupt declaration');
48
48
  keys.add(event.key);
49
49
  }
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.d.ts","sourceRoot":"","sources":["../../src/host/capabilities.js"],"names":[],"mappings":"AAcA,8FAA8F;AAC9F,0FASC;AAED,2FAA2F;AAC3F,iFAKC;AAED,gHAAgH;AAChH,mFA8BC;AA9DD,kGAAkG;AAClG;IACG,uDAMC;IAHE,aAA2C;IAC3C,YAA0B;IAC1B,gBAAkC;CAEvC"}
1
+ {"version":3,"file":"capabilities.d.ts","sourceRoot":"","sources":["../../src/host/capabilities.js"],"names":[],"mappings":"AAcA,8FAA8F;AAC9F,0FASC;AAED,2FAA2F;AAC3F,iFAKC;AAED,gHAAgH;AAChH,mFAsCC;AAtED,kGAAkG;AAClG;IACG,uDAMC;IAHE,aAA2C;IAC3C,YAA0B;IAC1B,gBAAkC;CAEvC"}
@@ -43,7 +43,16 @@ export function assertFlowHostCapabilities(flows, capabilities = {}) {
43
43
  for (const flow of flows) {
44
44
  if (flow?.safetyRevision !== undefined && (typeof flow.safetyRevision !== 'string' || !flow.safetyRevision.trim() || flow.safetyRevision !== flow.safetyRevision.trim()))
45
45
  throw new JSFEHostCapabilityError(flow?.id, CONTINUATION_SAFETY_REQUIREMENT, 'safetyRevision must be a nonempty unpadded string');
46
- const requirements = normalizeHostRequirements(flow?.variables?.contract?.value?.requires, flow?.id);
46
+ // Hosts admit raw JSON before the engine expands declarations. A native
47
+ // performer must retain the same explicit activation policy at that boundary.
48
+ const authored = flow?.declarationVersion !== undefined;
49
+ if (authored && flow.declarationVersion !== 1)
50
+ throw new JSFEHostCapabilityError(flow?.id, '', 'unsupported declarationVersion');
51
+ const requirements = normalizeHostRequirements([
52
+ ...normalizeHostRequirements(flow?.variables?.contract?.value?.requires, flow?.id),
53
+ ...(authored ? normalizeHostRequirements(flow?.contract?.requires, flow?.id) : []),
54
+ ...(authored && flow.performs !== undefined ? ['guardedActions'] : []),
55
+ ], flow?.id);
47
56
  for (const capability of requirements) {
48
57
  // Intrinsic runtime support, not a host option or an implicit host permission.
49
58
  if (capability === CONTINUATION_SAFETY_REQUIREMENT || capability === INPUT_PROPOSALS_REQUIREMENT || capability === CONTEXTUAL_RESPONSES_REQUIREMENT)
@@ -1 +1 @@
1
- {"version":3,"file":"registry-composition.d.ts","sourceRoot":"","sources":["../../src/host/registry-composition.js"],"names":[],"mappings":"AA8DA;;;;;GAKG;AACH;;;EAMC;AA1ED,sHAAsH;AACtH;IACG,0BAAgJ;IAAxC,aAAqC;CAC/I"}
1
+ {"version":3,"file":"registry-composition.d.ts","sourceRoot":"","sources":["../../src/host/registry-composition.js"],"names":[],"mappings":"AAmEA;;;;;GAKG;AACH;;;EAMC;AA/ED,sHAAsH;AACtH;IACG,0BAAgJ;IAAxC,aAAqC;CAC/I"}
@@ -70,9 +70,15 @@ function compose(registries, kind) {
70
70
  const entry = declaration;
71
71
  if (!plain(entry))
72
72
  fail(kind + ' entries must be declaration objects');
73
- const id = identity(entry.id, kind + ' ID'), name = identity(entry.name, kind + ' name');
74
- if (kind === 'flows' && !Array.isArray(entry.steps))
75
- fail('flow ' + id + ' needs a steps array');
73
+ const id = identity(entry.id, kind + ' ID');
74
+ const authored = kind === 'flows' && Object.hasOwn(entry, 'declarationVersion');
75
+ if (authored && entry.declarationVersion !== 1)
76
+ fail('flow ' + id + ' has unsupported declarationVersion');
77
+ // Composition preserves authored JSON; the engine compiles only after
78
+ // all selected sets are available. Mirror the builder's conventional alias.
79
+ const name = identity(authored && entry.name === undefined ? id.split(/[-:]/).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('') : entry.name, kind + ' name');
80
+ if (kind === 'flows' && !Array.isArray(entry.steps) && !(authored && (entry.form || entry.provides || entry.performs || entry.call || Array.isArray(entry.before) && entry.before.length)))
81
+ fail('flow ' + id + ' needs steps or a declarative form/provider/performer/worker');
76
82
  const bytes = JSON.stringify(canonical(entry));
77
83
  if (definitions.has(id)) {
78
84
  if (definitions.get(id) !== bytes)
package/dist/index.d.ts CHANGED
@@ -370,6 +370,12 @@ export interface FlowFrame {
370
370
  isolatedScope?: boolean;
371
371
  }
372
372
  export type Engine = WorkflowEngine;
373
+ /** Explicit JSON authoring input. The constructor lowers only version 1 declarations. */
374
+ export interface FlowDeclaration {
375
+ declarationVersion: 1;
376
+ id: string;
377
+ [key: string]: unknown;
378
+ }
373
379
  export interface FlowDefinition {
374
380
  id: string;
375
381
  name: string;
@@ -641,6 +647,12 @@ export declare class WorkflowEngine implements Engine {
641
647
  }>;
642
648
  cargo: Record<string, unknown> | undefined;
643
649
  flowsMenu: FlowDefinition[];
650
+ private readonly sourceFlowDeclarations;
651
+ private readonly namedFunctionNamespaces;
652
+ /** A detached authoring copy; engine compilation and validation never become editor source. */
653
+ getFlowDeclarations(): Array<FlowDefinition | FlowDeclaration>;
654
+ /** Engine-only lexical helpers for the current definition, never persisted in session variables. */
655
+ getNamedFunctionNamespace(): Record<string, unknown> | undefined;
644
656
  toolsRegistry: ToolDefinition[];
645
657
  APPROVED_FUNCTIONS: ApprovedFunctions;
646
658
  sessionId: string;
@@ -718,7 +730,7 @@ export declare class WorkflowEngine implements Engine {
718
730
  * // With custom timeout:
719
731
  * const engine = new WorkflowEngine(logger, aiCallback, flowsMenu, toolsRegistry, APPROVED_FUNCTIONS, [], true, 'en', 1000);
720
732
  */
721
- constructor(hostLogger: Logger | null, aiCallback: AiCallbackFunction, flowsMenu: FlowDefinition[], toolsRegistry: ToolDefinition[], APPROVED_FUNCTIONS: ApprovedFunctions, globalVariables?: Record<string, unknown>, // Optional global variables shared across all new flows
733
+ constructor(hostLogger: Logger | null, aiCallback: AiCallbackFunction, flowsMenu: Array<FlowDefinition | FlowDeclaration>, toolsRegistry: ToolDefinition[], APPROVED_FUNCTIONS: ApprovedFunctions, globalVariables?: Record<string, unknown>, // Optional global variables shared across all new flows
722
734
  validateOnInit?: boolean, language?: string, aiTimeOut?: number, // Optional AI timeout in milliseconds (default 2000ms)
723
735
  messageRegistry?: MessageRegistry, guidanceConfig?: GuidanceConfig);
724
736
  /**