jsfe 1.7.7 → 1.7.8

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 (45) hide show
  1. package/dist/forms/choice-flow.js +2 -2
  2. package/dist/forms/continuation-safety.d.ts +4 -0
  3. package/dist/forms/continuation-safety.d.ts.map +1 -0
  4. package/dist/forms/continuation-safety.js +14 -0
  5. package/dist/forms/contracts.d.ts.map +1 -1
  6. package/dist/forms/contracts.js +6 -4
  7. package/dist/forms/flows.d.ts.map +1 -1
  8. package/dist/forms/flows.js +45 -7
  9. package/dist/forms/identity-flows.d.ts.map +1 -1
  10. package/dist/forms/identity-flows.js +10 -3
  11. package/dist/forms/index.d.ts +1 -0
  12. package/dist/forms/index.d.ts.map +1 -1
  13. package/dist/forms/index.js +3 -1
  14. package/dist/helpers/answer.d.ts.map +1 -1
  15. package/dist/helpers/answer.js +10 -2
  16. package/dist/helpers/form-conversation.d.ts +22 -0
  17. package/dist/helpers/form-conversation.d.ts.map +1 -1
  18. package/dist/helpers/form-conversation.js +29 -1
  19. package/dist/helpers/form-state.d.ts +3 -2
  20. package/dist/helpers/form-state.d.ts.map +1 -1
  21. package/dist/helpers/form-state.js +93 -8
  22. package/dist/helpers/index.d.ts +13 -1
  23. package/dist/helpers/index.d.ts.map +1 -1
  24. package/dist/helpers/index.js +7 -5
  25. package/dist/helpers/match-inputs.d.ts.map +1 -1
  26. package/dist/helpers/match-inputs.js +7 -2
  27. package/dist/helpers/money.d.ts +4 -0
  28. package/dist/helpers/money.d.ts.map +1 -1
  29. package/dist/helpers/money.js +10 -1
  30. package/dist/helpers/semantic-input-prompt.d.ts +2 -0
  31. package/dist/helpers/semantic-input-prompt.d.ts.map +1 -0
  32. package/dist/helpers/semantic-input-prompt.js +153 -0
  33. package/dist/helpers/semantic-input.d.ts +28 -0
  34. package/dist/helpers/semantic-input.d.ts.map +1 -0
  35. package/dist/helpers/semantic-input.js +47 -0
  36. package/dist/host/capabilities.d.ts.map +1 -1
  37. package/dist/host/capabilities.js +5 -1
  38. package/dist/index.d.ts +20 -2
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +158 -1
  41. package/dist/runtime-identity.js +1 -1
  42. package/docs/copilot-reference.md +5 -0
  43. package/docs/development-release.md +12 -0
  44. package/docs/forms.md +44 -0
  45. package/package.json +1 -1
@@ -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_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(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
449
+ "value": "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"
450
450
  },
451
451
  {
452
452
  "id": "ac_switch_to_text_key",
@@ -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_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(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
620
+ "value": "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"
621
621
  },
622
622
  {
623
623
  "id": "ac_other_request_check",
@@ -0,0 +1,4 @@
1
+ export function withSafetyRevision(flow: any, revision: any): any;
2
+ export function continuationSafetyProtocol(): number;
3
+ export const CONTINUATION_SAFETY_REQUIREMENT: "jsfe:continuation-safety:v1";
4
+ //# sourceMappingURL=continuation-safety.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,14 @@
1
+ /** Opt in deliberately when a safety fix makes old serialized steps unsafe to resume. */
2
+ export const continuationSafetyProtocol = () => 1;
3
+ export const CONTINUATION_SAFETY_REQUIREMENT = 'jsfe:continuation-safety:v1';
4
+ export function withSafetyRevision(flow, revision) {
5
+ if (typeof revision !== 'string' || !revision.trim() || revision !== revision.trim())
6
+ throw new Error('safetyRevision requires a nonempty unpadded string');
7
+ const guard = { id: flow.id + '_continuation_safety_protocol', type: 'SET', variable: 'noop', value: 'continuationSafetyProtocol() === 1', requireTrue: true };
8
+ const steps = flow.steps.filter(step => step.id !== guard.id), original = flow.variables?.contract;
9
+ const variables = { noop: { type: 'boolean', scope: 'flow', value: false }, ...flow.variables };
10
+ // A safety upgrade does not invent a partial declarative FORM contract for legacy workers.
11
+ if (original)
12
+ 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
+ }
@@ -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;AACD;;;;;;;QAMC;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;AAsBD;;;QAEC;AACD;;;;;;;QAMC;AACD;;;QAGC;AACD;;;;;;;QA8BC;AAED,mHAAmH;AACnH,kDAgBC;AAED,+GAA+G;AAC/G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyEC"}
@@ -1,3 +1,4 @@
1
+ import { SEMANTIC_INPUT_REQUIREMENT, hasInputMeaning, validateSemanticInputStep, semanticInputRuntimeSteps } from '../helpers/semantic-input.js';
1
2
  import { CONTEXTUAL_RESPONSES_REQUIREMENT, 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';
@@ -84,7 +85,8 @@ function declared(flow, contract) {
84
85
  ...(step.branches ? { branches: Object.fromEntries(Object.entries(step.branches).map(([key, branch]) => [key, replacementDefaults(branch)])) } : {}),
85
86
  ...(step.onFail ? { onFail: replacementDefaults(step.onFail) } : {}) });
86
87
  const contextual = stepList(flow.steps).filter(step => step.type === 'DISPATCH').map(step => validateContextualResponseStep(step, flow)).some(Boolean);
87
- const requirements = [...normalizeHostRequirements(contract.requires, flow.id), ...(hasInputProposals(flow.variables?.inputs?.value) ? [INPUT_PROPOSALS_REQUIREMENT] : []), ...(contextual ? [CONTEXTUAL_RESPONSES_REQUIREMENT] : [])];
88
+ const semantic = stepList(flow.steps).filter(step => step.type === 'ASSESS-INPUT').map(step => validateSemanticInputStep(step, flow)).length > 0 || hasInputMeaning(flow.variables?.inputs?.value);
89
+ const requirements = [...normalizeHostRequirements(contract.requires, flow.id), ...(semantic ? [SEMANTIC_INPUT_REQUIREMENT] : []), ...(hasInputProposals(flow.variables?.inputs?.value) ? [INPUT_PROPOSALS_REQUIREMENT] : []), ...(contextual ? [CONTEXTUAL_RESPONSES_REQUIREMENT] : [])];
88
90
  const metadata = { version: 1, ...contract, parametersFrom: 'parameters' };
89
91
  if (requirements.length || contract.requires !== undefined)
90
92
  Object.defineProperty(metadata, 'requires', {
@@ -92,11 +94,11 @@ function declared(flow, contract) {
92
94
  });
93
95
  const guardedSteps = flow.steps.map(replacementDefaults);
94
96
  // Linking a form may declare it again. Rebuild an existing protocol-only prefix once.
95
- const rebuiltGuards = [...(requirements.includes(CONTEXTUAL_RESPONSES_REQUIREMENT) ? ['contextualResponseProtocol() === 1'] : []), ...(requirements.includes(INPUT_PROPOSALS_REQUIREMENT) ? ['formProposalProtocol() === 1'] : [])];
96
- if (requirements.includes(CONTEXTUAL_RESPONSES_REQUIREMENT))
97
+ const rebuiltGuards = [...(requirements.includes(SEMANTIC_INPUT_REQUIREMENT) ? ['semanticInputValidationProtocol() === 1'] : []), ...(requirements.includes(CONTEXTUAL_RESPONSES_REQUIREMENT) ? ['contextualResponseProtocol() === 1'] : []), ...(requirements.includes(INPUT_PROPOSALS_REQUIREMENT) ? ['formProposalProtocol() === 1'] : [])];
98
+ if (requirements.includes(CONTEXTUAL_RESPONSES_REQUIREMENT) || requirements.includes(SEMANTIC_INPUT_REQUIREMENT))
97
99
  while (guardedSteps[0]?.type === 'SET' && guardedSteps[0]?.requireTrue === true && rebuiltGuards.includes(guardedSteps[0]?.value))
98
100
  guardedSteps.shift();
99
- return { ...flow, steps: contextualResponseRuntimeSteps(flow.id, proposalRuntimeSteps(flow.id, guardedSteps, requirements), requirements), variables: { ...flow.variables, contract: value(metadata) } };
101
+ return { ...flow, steps: semanticInputRuntimeSteps(flow.id, contextualResponseRuntimeSteps(flow.id, proposalRuntimeSteps(flow.id, guardedSteps, requirements), requirements), requirements), variables: { ...flow.variables, contract: value(metadata) } };
100
102
  }
101
103
  export function defineWorker({ contract, ...flow }) {
102
104
  return declared({ scope: 'isolated', version: '1.0.0', ...flow }, contract);
@@ -1 +1 @@
1
- {"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/forms/flows.js"],"names":[],"mappings":"AA0FA;;;;;;GAMG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwDC;AACD;;;GAGG;AACH;;;;;;EAGC;AAkWD,wHAAwH;AACxH,wEAaC;AACD,4FAA4F;AAC5F;;;EAYC;AACD,sGAAsG;AACtG;;;EAOC;AAhgBM,6CAAuG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAorB9G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAOG"}
1
+ {"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/forms/flows.js"],"names":[],"mappings":"AA2FA;;;;;;GAMG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyDC;AACD;;;GAGG;AACH;;;;;;EAGC;AAmYD,wHAAwH;AACxH,wEAaC;AACD,4FAA4F;AAC5F;;;EAYC;AACD,sGAAsG;AACtG;;;EAOC;AAliBM,6CAAuG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAytB9G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAOG"}
@@ -1,3 +1,4 @@
1
+ import { SEMANTIC_INPUT_REQUIREMENT, hasInputMeaning, semanticInputRuntimeSteps } from '../helpers/semantic-input.js';
1
2
  /**
2
3
  * The FORM convention's system workers (owner direction and decisions 2026-10-19; spec: the jsfe-flow-designer skill,
3
4
  * references/collect-input-pattern.md and references/manifests.md). This file is their SOURCE: the flows below are
@@ -115,6 +116,7 @@ export function formFlow({ id, name, version, description, inputs, after = [], e
115
116
  id, name, version, description, scope, metadata: { formProtocol: 2 }, parameters: [...parameters, { name: 'form_instance', type: 'string', internal: true, description: 'Internal instance to resume' }], ...(primary ? { primary: true } : {}), ...(prompt ? { prompt, prompt_es } : {}),
116
117
  variables: vars({ form_on_exhausted: on_exhausted, form_incomplete_outcome: incompleteFrom ? null : incomplete_outcome, form_instance: '', form_internal_resume: false, form_resume_owner: '', form_arguments: {}, form_exhaustion: null, form_values: {}, form_validation: '', initial_readings: [], inputs: resolveFormInputs(inputs, FIELD_PRESETS), parent_form: '', result_input: '', questions: [], provides: null, exit_context: '', exit_context_es: '', form_confirm_q: '', form_confirm_q_es: '', form_confirmation: confirm || {}, form_should_confirm: false, ...extraVars }),
117
118
  steps: [
119
+ ...semanticInputRuntimeSteps(id, [], hasInputMeaning(inputs) ? [SEMANTIC_INPUT_REQUIREMENT] : []),
118
120
  ...proposalRuntimeSteps(id, [], hasInputProposals(inputs) ? [INPUT_PROPOSALS_REQUIREMENT] : []),
119
121
  SET(`${id}_resume_kind`, 'form_internal_resume', '!!form_instance'),
120
122
  SET(`${id}_open`, 'form_instance', `openFormInstance(cargo, ${JSON.stringify(id)}, inputs, { parent: parent_form || null, input: result_input || '', context:!!parent_form && !result_input, resume_on_parent_change: ${resume_on_parent_change === true}, resume: form_instance || (!parent_form ? (cargo.formTasks || {})[${JSON.stringify(id)}] || '' : ''), providers: provides, questions: questions, incomplete_outcome: ${incompleteExpression}, on_exhausted: form_on_exhausted })`),
@@ -166,7 +168,7 @@ const runForm = {
166
168
  variables: vars({ rf_stop: '', rf_resume: '', rf_resume_parent: false, rf_parent_resume: null, rf_status: '', rf_next: '', rf_next_form: '', rf_questions: [], rf_provides: null, rf_max: 0, rf_pending: [], rf_deferred: [], rf_proposal: null, rf_proposal_readings: [] }),
167
169
  steps: [
168
170
  SIDE('rf_resume_policy', '(rf_resume_parent === true && cargo.forms[rf_form] && cargo.forms[rf_form].context_only ? (cargo.forms[rf_form].resume_on_parent_change=true) : true, true)'),
169
- SET('rf_ancestor_resume', 'rf_parent_resume', 'formParentResume(cargo,rf_form,rf_resume_parent)'),
171
+ SET('rf_ancestor_resume', 'rf_parent_resume', 'formParentResume(cargo,rf_form,rf_resume_parent,nextFormProposal)'),
170
172
  WHEN('rf_ancestor_close', 'rf_parent_resume', SIDE('rf_ancestor_release', '(closeFormInstance(cargo,rf_parent_resume.child,false),true)')),
171
173
  WHEN('rf_ancestor_reboot', 'rf_parent_resume', FLOW('rf_ancestor_owner', 'resume-form', 'reboot', { form: '{{rf_parent_resume.owner}}' })),
172
174
  SIDE('rf_pass_count', '(cargo.forms[rf_form] ? (cargo.forms[rf_form].replays = Number(cargo.forms[rf_form].replays || 0) + 1) : true, true)'),
@@ -248,7 +250,7 @@ const collectInput = {
248
250
  WHEN('ci_route_key', 'ci_routed', FLOW('ci_route_key_flow', '{{ci_routed}}', 'call', { form: '{{form}}', input: '{{current}}' })),
249
251
  WHEN('ci_routed_end', 'ci_routed', END('ci_routed_done')),
250
252
  SET('ci_build_chain', 'ci_chain', CHAIN_JS),
251
- SET('ci_match', 'ci_m', "readFormAnswer(cargo.choiceText, ci_chain, ci_names.length > 1 ? { form: form, names: ci_names } : { form: form, name: current }, cargo.choice, provides && Array.isArray(questions) ? questions : [])"),
253
+ SET('ci_match', 'ci_m', "readFormAnswer(cargo.choiceText, ci_chain, Array.isArray(ci_spec.any_of) ? { form: form, names: ci_names } : { form: form, name: current }, cargo.choice, provides && Array.isArray(questions) ? questions : [])"),
252
254
  // The labels and validators ride on each reading, so the presets stay in this one flow.
253
255
  SET('ci_enrich', 'ci_m', 'enrichFormMatches(ci_m, ci_chain, form, ci_names, current)'),
254
256
  SET('ci_question_key', 'ci_qkey', "ci_m.questions.length ? ci_m.questions[0] : !ci_m.hits.length && !ci_m.ambiguous.length && Array.isArray(questions) && questions.length && provides ? pickChoice(cargo.choiceText, questions, false) : ''"),
@@ -283,7 +285,7 @@ const validateBatch = {
283
285
  id: 'validate-input-batch', name: 'ValidateInputBatch', version: '2.0.0', scope: 'isolated',
284
286
  description: 'Worker: validate dependency-ordered candidates; return accepted, rejected and pending readings before a single commit.',
285
287
  parameters: ['hits', 'accepted', 'rejected', 'pending', 'ignored'].map(name => ({ name, type: 'array' })),
286
- variables: vars({ accepted: [], rejected: [], pending: [], ignored: [], vb_h: null, vb_rest: [], vb_values: {}, vb_known: false, vb_ready: false, vb_relevant: false, vb_outcome: '', vb_candidate: null, vb_proposal_values: {}, vb_proposal: null, vb_proposal_ok: true }),
288
+ variables: vars({ accepted: [], rejected: [], pending: [], ignored: [], vb_h: null, vb_rest: [], vb_values: {}, vb_known: false, vb_ready: false, vb_relevant: false, vb_outcome: '', vb_candidate: null, vb_meaning: null, vb_semantic: null, vb_cancelled: null, vb_proposal_values: {}, vb_proposal: null, vb_proposal_ok: true }),
287
289
  steps: [
288
290
  SET('vb_init_accepted', 'accepted', 'Array.isArray(accepted) ? accepted : []'),
289
291
  SET('vb_init_rejected', 'rejected', 'Array.isArray(rejected) ? rejected : []'),
@@ -300,8 +302,16 @@ const validateBatch = {
300
302
  SET('vb_known', 'vb_known', "!!(!vb_h.revalidate && !vb_h.validate_always && cargo.forms[vb_h.form] && !cargo.forms[vb_h.form].errors[vb_h.name] && cargo.forms[vb_h.form].accepted[vb_h.name] && formValuesEqual(vb_values[vb_h.name], vb_h.value))"),
301
303
  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'))"),
302
304
  SIDE('vb_reset', "(cargo.inputCheck = vb_h.invalid ? { ok: false } : (vb_h.validator && !vb_known ? null : { ok: true, value: vb_h.value }), true)"),
303
- 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}}' })),
304
- WHEN('vb_refused', 'vb_h.refused === true', SIDE('vb_withhold_refusal', "(cargo.inputCheck=Object.assign({},cargo.inputCheck || {},{ok:false}),true)")),
305
+ SET('vb_meaning', 'vb_meaning', "(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.meaning || null;})()"),
306
+ SET('vb_semantic_reset', 'vb_semantic', "({ok:true,disposition:'accept'})"),
307
+ WHEN('vb_semantic_needed', 'vb_ready === true && vb_meaning && !vb_known && !vb_h.invalid', FLOW('vb_assess', 'assess-form-input', 'call', { form: '{{vb_h.form}}', input: '{{vb_h.name}}', value: '{{vb_h.value}}' })),
308
+ SET('vb_semantic_read', 'vb_semantic', "vb_ready === true && vb_meaning && !vb_known && !vb_h.invalid ? cargo.inputMeaningCheck : vb_semantic"),
309
+ WHEN('vb_semantic_cancelled', "vb_semantic && vb_semantic.disposition === 'cancel'", SET('vb_cancel_task', 'vb_cancelled', "cancelFormTask(cargo,vb_h.form)")),
310
+ WHEN('vb_cancel_dispatch', 'vb_cancelled', { id: 'vb_cancelled_dispatch', type: 'DISPATCH', outcome: '{{vb_cancelled.outcome}}', reason: '{{vb_cancelled.reason}}', recovery: { version: 1, mode: '{{vb_cancelled.recovery.mode}}', reason: '{{vb_cancelled.recovery.reason}}', form: "{{vb_cancelled.recovery.form || ''}}", flow: "{{vb_cancelled.recovery.flow || ''}}" } }),
311
+ WHEN('vb_semantic_redirect', "vb_semantic && vb_semantic.disposition === 'redirect'", yieldDispatch('vb_meaning_redirect', 'vb_h.form', "'input_request_changed'")),
312
+ WHEN('vb_meaning_rejected', '!vb_semantic || vb_semantic.ok !== true', SIDE('vb_withhold_meaning', "(cargo.inputCheck={ok:false,message:vb_semantic && vb_semantic.unavailable === true ? 'I could not validate that right now. Please try again.' : 'Please provide the requested information.',message_es:vb_semantic && vb_semantic.unavailable === true ? 'No pude validar eso en este momento. Por favor intente de nuevo.' : 'Por favor proporcione la información solicitada.'},true)")),
313
+ WHEN('vb_validator', 'vb_ready === true && vb_h.validator && !vb_known && !vb_h.invalid && vb_semantic && vb_semantic.ok === true', 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}}' })),
314
+ WHEN('vb_refused', 'vb_h.refused === true || vb_h.incompleteMoney === true', SIDE('vb_withhold_refusal', "(cargo.inputCheck=Object.assign({},cargo.inputCheck || {},{ok:false}),true)")),
305
315
  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})"),
306
316
  SET('vb_proposal_policy', 'vb_proposal', 'vb_relevant === true && vb_ready === true && vb_candidate.ok && !vb_known ? formProposalPolicy(cargo,vb_candidate,cargo.inputCheck,accepted) : null'),
307
317
  SET('vb_proposal_values', 'vb_proposal_values', 'proposedFormValues(cargo,vb_h.form,accepted.concat([vb_candidate]))'),
@@ -313,6 +323,31 @@ const validateBatch = {
313
323
  FLOW('vb_next', 'validate-input-batch', 'replace', { hits: '{{vb_rest}}', accepted: '{{accepted}}', rejected: '{{rejected}}', pending: '{{pending}}', ignored: '{{ignored}}' }),
314
324
  ],
315
325
  };
326
+ const requestCancelled = {
327
+ id: 'request-cancelled', name: 'RequestCancelled', version: '1.0.0', scope: 'isolated', description: 'Retire an explicitly withdrawn owning request and acknowledge it; preserve unknown actions for reconciliation.',
328
+ parameters: [{ name: 'form', type: 'string' }], variables: vars({ form: '', cancelled: null }),
329
+ steps: [SET('cancel_request_owner', 'cancelled', 'cancelFormTask(cargo,form)'),
330
+ { id: 'cancel_request_notice', type: 'SAY', value: "{{cancelled.recovery.mode === 'hold' ? 'The result of your earlier request is still unknown. Our team needs to check it before another attempt.' : 'Okay, I stopped this request. Is there anything else I can help you with?'}}", value_es: "{{cancelled.recovery.mode === 'hold' ? 'El resultado de su solicitud anterior sigue sin confirmarse. Nuestro equipo debe revisarlo antes de otro intento.' : 'De acuerdo, detuve esta solicitud. ¿Hay algo más en lo que le pueda ayudar?'}}", outcome: '{{cancelled.outcome}}', reason: '{{cancelled.reason}}', recovery: { version: 1, mode: '{{cancelled.recovery.mode}}', reason: '{{cancelled.recovery.reason}}', form: "{{cancelled.recovery.form || ''}}", flow: "{{cancelled.recovery.flow || ''}}" } }]
331
+ };
332
+ const assessFormInput = {
333
+ id: 'assess-form-input', name: 'AssessFormInput', version: '1.0.0', scope: 'isolated', description: 'Validate a candidate against the owning field’s declared meaning without changing its words or authorizing actions.',
334
+ parameters: [{ name: 'form', type: 'string' }, { name: 'input', type: 'string' }, { name: 'value', type: 'string' }],
335
+ variables: vars({ group: null, spec: null, purpose: '', acceptance: '', question: '', assessment: null }),
336
+ steps: [SET('meaning_group', 'group', "cargo.forms[form].specs.find(function(s){return s.name===input || s.any_of && s.any_of.some(function(member){return member.name===input;});})"), SET('meaning_spec', 'spec', "group && (group.any_of ? group.any_of.find(function(s){return s.name===input;}) : group)"),
337
+ { ...SET('meaning_declared', 'noop', '!!spec && !!spec.meaning && !!validateInputMeaning(spec.meaning)'), requireTrue: true },
338
+ SET('meaning_question', 'question', "formInputPrompt(cargo,form,input,Object.assign({},group,spec,{question:spec.question || group.question,question_es:spec.question_es || group.question_es,question_from:spec.question_from || group.question_from}),cargo.forms[form].data || {},language)"),
339
+ SET('meaning_purpose', 'purpose', 'spec.meaning.purpose'), SET('meaning_acceptance', 'acceptance', 'spec.meaning.acceptance'),
340
+ { id: 'meaning_assess', type: 'ASSESS-INPUT', value: '{{value}}', question: '{{question}}', purpose: '{{purpose}}', acceptance: '{{acceptance}}', variable: 'assessment' },
341
+ SIDE('meaning_result', '(cargo.inputMeaningCheck=assessment,true)')]
342
+ };
343
+ // Adapter for legacy callers: the same optional semantic contract and bounded FORM lifecycle.
344
+ const collectSemanticAnswer = formFlow({ id: 'collect-semantic-answer', name: 'CollectSemanticAnswer', description: 'Collect one meaningful field using explicit purpose and acceptance criteria, preserving the caller’s wording.',
345
+ parameters: [...['question', 'question_es', 'purpose', 'acceptance', 'context', 'context_es'].map(name => ({ name, type: 'string' })), { name: 'choices', type: 'array' }, { name: 'digits', type: 'object' }],
346
+ extraVars: { question: '', question_es: '', purpose: '', acceptance: '', context: 'your request', context_es: 'su solicitud', choices: [], digits: null },
347
+ inputs: [{ name: 'answer', profile: { kind: 'text', narrative: true }, meaning: { purpose: 'Use the caller declaration supplied to this collector.', acceptance: 'Use the caller acceptance criteria supplied to this collector.' }, question_from: 'question' }],
348
+ before: [{ ...SET('semantic_policy_required', 'noop', "typeof purpose==='string' && !!purpose.trim() && typeof acceptance==='string' && !!acceptance.trim()"), requireTrue: true },
349
+ SIDE('semantic_declaration', "(function(){var state=cargo.forms[form_instance];state.data={question:question,question_es:question_es};state.specs[0].meaning={purpose:purpose,acceptance:acceptance};state.specs[0].profile=choices.length ? {kind:'choice',choices:choices,accept_other:true,narrative:true} : {kind:'text',narrative:true};state.specs[0].digits=digits;return true;})()"), SET('semantic_context', 'exit_context', 'context'), SET('semantic_context_es', 'exit_context_es', 'context_es')],
350
+ after: [SIDE('semantic_return', "(cargo.semanticAnswer={value:cargo.forms[form_instance].values.answer,raw:String(cargo.choiceText || '')},cargo.choice=cargo.semanticAnswer.value,cargo.choiceText=cargo.semanticAnswer.raw,true)")] });
316
351
  const accept = {
317
352
  id: 'collect-input-accept', name: 'CollectInputAccept', version: '2.0.0', scope: 'isolated',
318
353
  description: 'Worker: validate all readings, commit accepted changes once with transitive invalidation, then acknowledge and run declared callbacks.',
@@ -711,13 +746,16 @@ const resumeForm = { id: 'resume-form', name: 'ResumeForm', version: '1.0.0', sc
711
746
  SET('resume_definition', 'target', 'cargo.forms[form].definition'), SET('resume_parent', 'parent', "cargo.forms[form].parent || ''"), SET('resume_slot', 'slot', "cargo.forms[form].result_input || ''"),
712
747
  FLOW('resume_owned_form', '{{target}}', 'replace', { form_instance: '{{form}}', parent_form: '{{parent}}', result_input: '{{slot}}' })
713
748
  ] };
714
- const LIBRARY_FLOWS = [confirmInputProposal, proposalDeclined, resumeForm, performAction, sendTextAction, prepareInput, runForm, collectInput, validateBatch, accept, acceptedEffects, disambiguate, confirmForm, formDone, providerMenu, ...validators, ...fieldCollectors, ...subForms, provideData, provideQueuedData, loadSource, answerFacts];
749
+ const LIBRARY_FLOWS = [confirmInputProposal, proposalDeclined, resumeForm, performAction, sendTextAction, prepareInput, runForm, collectInput, validateBatch, requestCancelled, assessFormInput, collectSemanticAnswer, accept, acceptedEffects, disambiguate, confirmForm, formDone, providerMenu, ...validators, ...fieldCollectors, ...subForms, provideData, provideQueuedData, loadSource, answerFacts];
715
750
  const LIBRARY_CONTRACTS = {
716
751
  'confirm-input-proposal': { role: 'collector', requires: [INPUT_PROPOSALS_REQUIREMENT] }, 'confirm-input-proposal-declined': { role: 'worker', requires: [INPUT_PROPOSALS_REQUIREMENT] },
717
752
  'resume-form': { role: 'worker' },
718
753
  'perform-action': { role: 'worker', tools: ['jsfe:action-claim', 'jsfe:action-complete'], result: { path: 'cargo.actionResult', type: 'object' } },
719
754
  'send-text-action': { role: 'worker', result: { path: 'cargo.actionOutcome', type: 'object' } },
720
755
  'prepare-input': { role: 'worker' }, 'run-form': { role: 'worker' }, 'collect-input': { role: 'worker' },
756
+ 'request-cancelled': { role: 'worker', requires: [SEMANTIC_INPUT_REQUIREMENT] },
757
+ 'assess-form-input': { role: 'worker', requires: [SEMANTIC_INPUT_REQUIREMENT], result: { path: 'cargo.inputMeaningCheck', type: 'object' } },
758
+ 'collect-semantic-answer': { role: 'collector', requires: [SEMANTIC_INPUT_REQUIREMENT] },
721
759
  'validate-input-batch': { role: 'worker', result: { path: 'cargo.inputBatch', type: 'object' } },
722
760
  'collect-input-accept': { role: 'worker' }, 'input-accepted-effects': { role: 'worker' },
723
761
  'disambiguate-input': { role: 'worker' }, 'confirm-form': { role: 'worker' }, 'form-done': { role: 'worker' },
@@ -738,6 +776,6 @@ export const FLOWS = LIBRARY_FLOWS.map(flow => {
738
776
  throw new Error('Shared worker needs an explicit contract: ' + flow.id);
739
777
  if ((declaration.role === 'collector') !== (flow.metadata?.formProtocol === 2))
740
778
  throw new Error('Shared collector contract mismatch: ' + flow.id);
741
- return { ...flow, steps: proposalRuntimeSteps(flow.id, flow.steps, declaration.requires), variables: { ...flow.variables, contract: { type: 'object', value: { version: 1, summary: flow.description,
779
+ return { ...flow, steps: semanticInputRuntimeSteps(flow.id, proposalRuntimeSteps(flow.id, flow.steps, declaration.requires), declaration.requires), variables: { ...flow.variables, contract: { type: 'object', value: { version: 1, summary: flow.description,
742
780
  parametersFrom: 'parameters', ...declaration, ...(declaration.role === 'collector' ? { form: { inputs: 'inputs' } } : {}) } } } };
743
781
  });
@@ -1 +1 @@
1
- {"version":3,"file":"identity-flows.d.ts","sourceRoot":"","sources":["../../src/forms/identity-flows.js"],"names":[],"mappings":"AA2BA,+GAA+G;AAC/G,oFAOC;AAQD,wFAAwF;AACxF,iDAGC;AACD,6CAMC;AACD,qHAQC;AAMD,4EAKC;AAgFD,4DAKC;AAwED,8EAGC;AA4BD,4FAA4F;AAC5F;;;;EAOC;AAQD,0BAAmI"}
1
+ {"version":3,"file":"identity-flows.d.ts","sourceRoot":"","sources":["../../src/forms/identity-flows.js"],"names":[],"mappings":"AA2BA,+GAA+G;AAC/G,oFAOC;AAQD,wFAAwF;AACxF,iDAGC;AACD,6CAMC;AACD,qHAQC;AAMD,4EAKC;AAgFD,4DAKC;AA+ED,8EAGC;AA4BD,4FAA4F;AAC5F;;;;EAOC;AAQD,0BAAmI"}
@@ -111,7 +111,7 @@ const contact = worker('get-cell-or-email', 'GetCellOrEmail', 'Identify a suppli
111
111
  when('identity_contact_split_overshoot', "contact_partial && contact_digits.length > (contact_options.account_shape || []).reduce(function(max,s){return Math.max(max,Math.max.apply(null,s.lengths || [0]));},0)", call('identity_contact_restart_split', 'contact-split-failed', { contact_options: '{{contact_options}}' }, 'replace')),
112
112
  set('identity_contact_identifier', 'contact_id', "contact_options.account_pattern ? readIdentifier(contact_text,contact_options.account_pattern) : null"),
113
113
  set('identity_contact_phone', 'contact_phone', "readPhone(contact_text) || (validatePhone(contact_digits) ? contact_digits : '')"), set('identity_contact_email', 'contact_mail', 'readEmail(contact_text)'),
114
- set('identity_contact_classify', 'contact_kind', "contact_id && contact_id.kind === 'account' ? 'account' : contact_phone ? 'phone' : contact_mail ? 'email' : readInternationalPhone(contact_text) ? 'international' : isAgentRequest(contact_text) ? 'agent' : isAnswer(contact_text,'exit') && contact_text.trim().split(/\\s+/).length <= 2 ? 'exit' : contact_allowed && /^(?:no|nope|nah)\\b/i.test(contact_text.trim()) && !/[0-9@]/.test(contact_text) ? 'decline' : contact_allowed ? 'caller' : contact_digits ? 'invalid_phone' : contact_text.trim().split(/\\s+/).length>=3 && !/[0-9@]/.test(contact_text) ? 'unmapped' : 'invalid'"),
114
+ set('identity_contact_classify', 'contact_kind', "contact_id && contact_id.kind === 'account' ? 'account' : contact_phone ? 'phone' : contact_mail ? 'email' : readInternationalPhone(contact_text) ? 'international' : isAgentRequest(contact_text) ? 'agent' : isAnswer(contact_text,'exit') && contact_text.trim().split(/\\s+/).length <= 2 ? 'exit' : contact_allowed && /^(?:no|nope|nah)\\b/i.test(contact_text.trim()) && !/[0-9@]/.test(contact_text) ? 'decline' : contact_allowed && cargo.serviceAnswer && cargo.serviceAnswer.values.caller_decision === 'yes' ? 'caller' : contact_digits ? 'invalid_phone' : contact_text.trim().split(/\\s+/).length>=3 && !/[0-9@]/.test(contact_text) ? 'unmapped' : 'invalid'"),
115
115
  set('identity_contact_error', 'contact_error', expression(contactError, 'contact_kind', 'contact_options')), set('identity_contact_error_es', 'contact_error_es', expression(contactError, 'contact_kind', 'contact_options', 'true')),
116
116
  cases('identity_contact_route', {
117
117
  "condition: contact_kind === 'agent'": call('identity_contact_agent', 'live-agent-requested', undefined, 'reboot'),
@@ -164,7 +164,7 @@ const auth = worker('authenticate-user', 'AuthenticateUser', 'Authenticate a con
164
164
  effect('auth_challenge_init', "(cargo.otpLateCode='',cargo.otpResends=0,cargo.otpMismatches=0,cargo.otpFormatMisses=0,cargo.otpWordMisses=0,cargo.otp_cell_number=cell_number || '',cargo.otp_email=email || '',true)"),
165
165
  call('auth_send', 'send-otp-code'), when('auth_send_failed', 'cargo.otpSendFailure', call('auth_send_failure', 'otp-send-failed', undefined, 'replace')),
166
166
  call('auth_code', 'get-and-validate-otp-code'),
167
- cases('auth_complete', { 'condition: cargo.otpVerified === true': set('auth_ok', 'auth_result', 'true'), 'condition: cargo.authRetry': end('auth_return_retry'), default: otpMenu('auth_retry_code', 'Sorry, the code you entered was invalid or expired.', 'Lo siento, el código que ingresó era inválido o había expirado.', true) }),
167
+ cases('auth_complete', { 'condition: cargo.otpVerified === true': set('auth_ok', 'auth_result', 'true'), 'condition: cargo.authRetry': end('auth_return_retry'), default: otpMenu('auth_retry_code', "I couldn't verify your account. You can try again or use another contact.", 'No pude verificar su cuenta. Puede intentarlo de nuevo o usar otro contacto.', true) }),
168
168
  call('auth_gate_end', 'task-gate', { form: '{{parent_form}}', gate: 'authenticate-user', active: false })
169
169
  ] });
170
170
  export function otpPrompt(cargo, es = false) {
@@ -189,6 +189,13 @@ const OTP_WORDS = {
189
189
  later: ['driving', 'i am driving', 'i m busy', 'im busy', 'not now', 'later', 'call me later', 'call back', 'cant right now', 'can t right now', 'can t now', 'cannot right now', 'manejando', 'conduciendo', 'estoy manejando', 'voy manejando', 'ahora no', 'ahora no puedo', 'no puedo ahora', 'más tarde', 'mas tarde', 'estoy ocupado', 'estoy ocupada'],
190
190
  noPhone: ['don t have that phone', 'don t have that number', 'don t have that phone anymore', 'don t have the phone', 'not my number anymore', 'not my phone anymore', 'that s an old number', 'old number', 'changed my number', 'changed my phone', 'lost my phone', 'no tengo ese teléfono', 'no tengo ese telefono', 'no tengo ese número', 'no tengo ese numero', 'ya no tengo ese', 'ya no tengo el teléfono', 'ya no tengo el telefono', 'ya no es mi número', 'ya no es mi numero', 'número viejo', 'numero viejo', 'cambié de número', 'cambie de numero', 'cambié mi número', 'perdí mi teléfono', 'perdi mi telefono', 'don t have a phone', 'don t have phone', 'don t have my phone', 'don t have a cell', 'don t have the cell', 'don t have my cell', 'don t have a cell phone', 'don t have access to that phone', 'don t have access to the phone', 'no tengo teléfono', 'no tengo telefono', 'no tengo celular', 'no tengo el celular', 'no tengo mi teléfono', 'no tengo mi telefono', 'no tengo mi celular', 'no tengo un teléfono', 'no tengo un telefono', 'no tengo acceso a ese teléfono', 'no tengo acceso a ese telefono']
191
191
  };
192
+ /** Contact access is a protocol state, not an OTP-format error. Read negative possession/access grammar
193
+ * around the phone referent, including "no longer have", without treating an unrelated NO as a contact change. */
194
+ function otpPhoneUnavailable(value) {
195
+ const text = String(value || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[’]/g, "'");
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
+ || /\b(?:ya\s+no|no)\s+(?:tengo|puedo\s+(?:usar|acceder))\b[^.!?]{0,70}\b(?:telefono|numero|celular|movil)\b/.test(text);
198
+ }
192
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: [
193
200
  set('otp_cancel', 'otp_cancel', "cargo.authCancelFlow || 'contact-support'"),
194
201
  set('otp_reset_no_code', 'no_code_given', 'false'), set('otp_reset_invite', 'whatsapp_invite_sent', 'false'), set('otp_reset_callback', 'answer_key', "''"),
@@ -206,7 +213,7 @@ const validateCode = worker('validate-otp-code', 'ValidateOtpCode', 'Validate a
206
213
  'condition: matchesChoice(user_choice,otp_words.later)': say('otp_later', "No problem. Say TEXT and I'll continue with you by message so you can do this when you are free, or {{cargo.verb}} the code whenever you are ready.", 'No hay problema. Diga TEXTO y sigo con usted por mensaje para que lo haga cuando esté libre, o {{cargo.verb_es}} el código cuando pueda.'),
207
214
  'condition: normalized_otp_code.length > 0 && Number(cargo.otpFormatMisses || 0)<2': say('otp_bad_format', "I was expecting a 6-digit code. Let's try again. You can also {{cargo.voice ? 'press * or ' : ''}}{{cargo.verb}} EXIT to cancel.", "Esperaba un código de 6 dígitos. Intentemos de nuevo. También puede {{cargo.voice ? 'presionar * o decir' : 'escribir'}} SALIR para cancelar."),
208
215
  'condition: normalized_otp_code.length > 0': effect('otp_format_cap_next', 'true'),
209
- 'condition: matchesChoice(user_choice,otp_words.noPhone)': otpMenu('otp_no_phone', "No problem. Then the code can't reach you there. You can use the email on your account instead, or {{cargo.verb}} AGENT to reach a person.", 'No hay problema. Entonces el código no le puede llegar ahí. Puede usar el correo electrónico de su cuenta, o {{cargo.verb_es}} AGENTE para hablar con una persona.', false),
216
+ ['condition: matchesChoice(user_choice,otp_words.noPhone) || ' + expression(otpPhoneUnavailable, 'user_choice')]: otpMenu('otp_no_phone', "No problem. Then the code can't reach you there. You can use the email on your account instead, or {{cargo.verb}} AGENT to reach a person.", 'No hay problema. Entonces el código no le puede llegar ahí. Puede usar el correo electrónico de su cuenta, o {{cargo.verb_es}} AGENTE para hablar con una persona.', false),
210
217
  default: set('otp_words_missing', 'no_code_given', 'true')
211
218
  }),
212
219
  effect('otp_word_count', '(cargo.otpWordMisses=Number(cargo.otpWordMisses || 0)+(no_code_given?1:0),true)'),
@@ -1,6 +1,7 @@
1
1
  export const FLOWS: any[];
2
2
  export { FLOWS as IDENTITY_FLOWS } from "./identity-flows.js";
3
3
  export { compileFormPrompts } from "./prompt-compiler.js";
4
+ export { withSafetyRevision, CONTINUATION_SAFETY_REQUIREMENT } from "./continuation-safety.js";
4
5
  export { FIELD_PRESETS, formFlow, declinedFlow, textValue } from "./flows.js";
5
6
  export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from "./contracts.js";
6
7
  export { addressDraft, zipLocation, streetLocation, resolvedAddress } from "../helpers/address.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.js"],"names":[],"mappings":"AAIA,0BAAgF"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.js"],"names":[],"mappings":"AAMA,0BAAiJ"}
@@ -1,8 +1,10 @@
1
+ import { withSafetyRevision } from './continuation-safety.js';
2
+ export { withSafetyRevision, CONTINUATION_SAFETY_REQUIREMENT } from './continuation-safety.js';
1
3
  import { FLOWS as ADDRESS_FLOWS } from './address-flows.js';
2
4
  import { FLOWS as FORM_FLOWS } from './flows.js';
3
5
  import { FLOWS as CHOICE_FLOWS } from './choice-flow.js';
4
6
  import { FLOWS as IDENTITY } from './identity-flows.js';
5
- export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY];
7
+ export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY].map(flow => withSafetyRevision(flow, 'consent-routing-2026-10-22'));
6
8
  export { FIELD_PRESETS, formFlow, declinedFlow, textValue } from './flows.js';
7
9
  export { FLOWS as IDENTITY_FLOWS } from './identity-flows.js';
8
10
  export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from './contracts.js';
@@ -1 +1 @@
1
- {"version":3,"file":"answer.d.ts","sourceRoot":"","sources":["../../src/helpers/answer.js"],"names":[],"mappings":"AAuLA;;;GAGG;AACH,wEAkBC;AAED,+HAA+H;AAC/H,oDAIC;AAcD,2GAA2G;AAC3G,uDAGC;AAOD;;;;;GAKG;AACH,+DAUC;AAKD;;;;GAIG;AACH,oDAEC;AAiBD;;;;;;GAMG;AACH,mDAAmF;AAEnF,kGAAkG;AAClG;;;EA6BC;AAUD;;;;;;;;;GASG;AACH,6EAyGC;;;;;;;;AApZD,qCAKiD"}
1
+ {"version":3,"file":"answer.d.ts","sourceRoot":"","sources":["../../src/helpers/answer.js"],"names":[],"mappings":"AAuLA;;;GAGG;AACH,wEAkBC;AAED,+HAA+H;AAC/H,oDAIC;AAcD,2GAA2G;AAC3G,uDAGC;AAOD;;;;;GAKG;AACH,+DAUC;AAKD;;;;GAIG;AACH,oDAEC;AAiBD;;;;;;GAMG;AACH,mDAAmF;AAEnF,kGAAkG;AAClG;;;EAmCC;AAUD;;;;;;;;;GASG;AACH,6EAyGC;;;;;;;;AA1ZD,qCAKiD"}
@@ -56,7 +56,7 @@ const NEGATIONS = ['no', 'not', 'nope', 'nah', 'never', 'dont', 'doesnt', 'didnt
56
56
  // Phrases that hold a negation word but agree ("no problem", "why not").
57
57
  const AGREEING = /\b(no problem|no worries|no hay problema|no te preocupes|why not|por que no|por qué no)\b/g;
58
58
  const DEFERRAL = /\b(later|tomorrow|next week|not now|not today|another time|mañana|manana|después|despues|luego|otro día|otro dia|ahora no|hoy no)\b/;
59
- const AGENT_ONLY = /^(?:(?:i want|i need|i would like|id like|can i|could i|let me|please|quiero|necesito|puedo|por favor)\s+)*(?:(?:to\s+)?(?:talk|speak|hablar|comunicarme)\s+(?:to|with|con)\s+)?(?:a|an|un|una|el|la)?\s*(?:live agent|agent|representative|rep|human|operator|real person|a person|person|someone|somebody|customer service|agente|representante|humano|operador|operadora|persona|alguien|servicio al cliente|gerente|manager|supervisor)(?:\s+(?:please|por favor))?$/;
59
+ const AGENT_ONLY = /^(?:(?:i want|i need|i would like|id like|can i|could i|let me|please|quiero|necesito|puedo|por favor)\s+)*(?:(?:to\s+)?(?:talk|speak|hablar|comunicarme)\s+(?:to|with|con)\s+)?(?:a|an|un|una|el|la)?\s*(?:live agent|agent|representative|rep|human|operator|real person|a person|person|someone|somebody|customer service|agente|representante|humano|operador|operadora|persona|alguien|servicio al cliente|agente en vivo|gerente|manager|supervisor)(?:\s+(?:please|por favor))?$/;
60
60
  // Accents are not meaning here (owner 2026-10-16): text callers type "direccion" for "dirección", "si" for "sí". Both
61
61
  // sides of every comparison pass through normalize, so a word list matches with or without them; ñ is kept.
62
62
  const plainVowels = (s) => s.replace(/[áàâä]/g, 'a').replace(/[éèêë]/g, 'e').replace(/[íìîï]/g, 'i').replace(/[óòôö]/g, 'o').replace(/[úùûü]/g, 'u');
@@ -273,7 +273,7 @@ export function isAmountAnswer(input) {
273
273
  return AMOUNT_ANSWER.test(String(input ?? '').replace(/\\(['"\\])/g, '$1'));
274
274
  }
275
275
  // A number that names something other than an amount: an account or sub-account, a card's last digits, a code, a ZIP.
276
- const IDENTIFIER_NUMBER = /\b(?:sub[\s-]?accounts?|accounts?|subcuentas?|cuentas?|cards?|tarjetas?|ending(?:\s+in)?|terminad[ao]s?\s+en|que\s+termina\s+en|termina\s+en|codes?|c[oó]digos?|zip(?:\s+code)?|postal|n[uú]mero|number)\s*(?:de\s+|is\s+|es\s+)?\d[\d\s-]*/gi;
276
+ const IDENTIFIER_NUMBER = /\b(?:sub[\s-]?accounts?|accounts?|subcuentas?|cuentas?|cards?|tarjetas?|ending(?:\s+in)?|terminad[ao]s?\s+en|que\s+termina(?:\s+en)?|termina(?:\s+en)?|codes?|c[oó]digos?|zip(?:\s+code)?|postal|n[uú]mero|number)\s*(?:de\s+|is\s+|es\s+)?\d[\d\s-]*/gi;
277
277
  // Digits spoken one at a time ("2 4 8 6"): a card ending or a code read back, never an amount.
278
278
  const SPELLED_DIGITS = /\b\d(?:\s+\d\b){2,}/g;
279
279
  // "10 con 18 centavos", "10 dollars and 18 cents", "$10 y 18 centavos"; speech-to-text also writes "76 con50 centavos", and
@@ -297,6 +297,14 @@ export function amountInAnswer(input) { return numericAmountReading(input).value
297
297
  /** Internal numeric evidence shared by the opt-in money reader; legacy results stay unchanged. */
298
298
  export function numericAmountReading(input) {
299
299
  const raw = String(input ?? '').replace(/\\(['"\\])/g, '$1');
300
+ // A connector plus cents is a fragment of another amount, not a new standalone payment.
301
+ // A caller can instead explicitly request "51 cents" or provide the complete dollars and cents.
302
+ if (/^\s*(?:and|con|y)\s*(?:un\s+)?\d{1,2}\s*(?:cents?|centavos?)\b/i.test(raw))
303
+ return { value: NaN, candidates: 0 };
304
+ // Last-four references (including a repeated unlabelled number) do not supply an amount.
305
+ // Mixed answers with an explicit monetary marker or payment verb still parse their independent amount.
306
+ if (/\b(?:cards?|tarjetas?|ending|termina(?:d[ao]s?)?|visa|mastercard|amex|discover)\b/i.test(raw) && !isAmountAnswer(raw) && !/\b(?:pay|paying|pagar|abonar)(?:\b|(?=\d))/i.test(raw))
307
+ return { value: NaN, candidates: 0 };
300
308
  // 1.234,56 (European) → 1234.56; 1,234.56 → 1234.56; 12,50 → 12.50
301
309
  let t = /\d{1,3}(\.\d{3})+,\d{1,2}\b/.test(raw) ? raw.replace(/\./g, '').replace(',', '.') : raw.replace(/,(?=\d{3}\b)/g, '').replace(/(\d),(\d{1,2})\b/g, '$1.$2');
302
310
  const dc = t.match(DOLLARS_AND_CENTS);
@@ -25,4 +25,26 @@ export function formConversationOutcome(cargo: any, id: any, reason: any, failur
25
25
  flow: any;
26
26
  };
27
27
  };
28
+ /** An explicit withdrawal retires the owning task; unknown actions remain held for reconciliation. */
29
+ export function cancelFormTask(cargo: any, id: any): {
30
+ outcome: any;
31
+ reason: any;
32
+ recovery: {
33
+ version: number;
34
+ mode: string;
35
+ reason: any;
36
+ form?: undefined;
37
+ flow?: undefined;
38
+ };
39
+ } | {
40
+ outcome: any;
41
+ reason: any;
42
+ recovery: {
43
+ version: number;
44
+ mode: string;
45
+ reason: any;
46
+ form: any;
47
+ flow: any;
48
+ };
49
+ };
28
50
  //# sourceMappingURL=form-conversation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"form-conversation.d.ts","sourceRoot":"","sources":["../../src/helpers/form-conversation.js"],"names":[],"mappings":"AAGA,0EAGC;AACD,oEAGC;AACD,sGAAsG;AACtG,+GAMC;AACD,8EAAwI;AAExI,yGAAyG;AACzG;;;;;;;;;;;;;;;;;;;;EAUC"}
1
+ {"version":3,"file":"form-conversation.d.ts","sourceRoot":"","sources":["../../src/helpers/form-conversation.js"],"names":[],"mappings":"AAGA,0EAGC;AACD,oEAGC;AACD,sGAAsG;AACtG,+GAMC;AACD,8EAAwI;AAExI,yGAAyG;AACzG;;;;;;;;;;;;;;;;;;;;EAUC;AAED,sGAAsG;AACtG;;;;;;;;;;;;;;;;;;;;EAeC"}
@@ -1,5 +1,5 @@
1
1
  /** Shared FORM retry, contextual yield and recovery policy; all state is conversation-owned. */
2
- import { formIncompleteOutcome } from './form-state.js';
2
+ import { formIncompleteOutcome, closeFormInstance } from './form-state.js';
3
3
  export function clearFormMisses(cargo, id, input) {
4
4
  const state = cargo.forms?.[id];
5
5
  if (!state)
@@ -55,3 +55,31 @@ export function formConversationOutcome(cargo, id, reason, failure = false, reco
55
55
  const mode = unknown ? 'hold' : recoveryMode, why = unknown ? 'action_result_unknown' : completed.owner ? completed.reason : reason;
56
56
  return { outcome: unknown ? 'unresolved' : completed.owner ? completed.outcome : failure ? 'unresolved' : 'pending', reason: why, recovery: { version: 1, mode, reason: why, form: root.id, flow: root.definition } };
57
57
  }
58
+ /** An explicit withdrawal retires the owning task; unknown actions remain held for reconciliation. */
59
+ export function cancelFormTask(cargo, id) {
60
+ // A completed primary may own an optional follow-up with an unknown send result.
61
+ // That completion does not permit withdrawing the unresolved action's evidence.
62
+ let root = cargo.forms?.[id];
63
+ const ancestors = new Set();
64
+ while (root?.parent && cargo.forms?.[root.parent] && !ancestors.has(root.id)) {
65
+ ancestors.add(root.id);
66
+ root = cargo.forms[root.parent];
67
+ }
68
+ if (root) {
69
+ const belongs = state => { const seen = new Set(); while (state && !seen.has(state.id)) {
70
+ if (state.id === root.id)
71
+ return true;
72
+ seen.add(state.id);
73
+ state = cargo.forms?.[state.parent];
74
+ } return false; };
75
+ const unknown = Object.values(cargo.forms || {}).filter(belongs).some(state => Object.values(state.actions || {}).some(record => ['attempted', 'unknown'].includes(record.status)));
76
+ if (unknown)
77
+ return { outcome: 'unresolved', reason: 'action_result_unknown', recovery: { version: 1, mode: 'hold', reason: 'action_result_unknown', form: root.id, flow: root.definition } };
78
+ }
79
+ const outcome = formConversationOutcome(cargo, id, 'request_cancelled', false, 'none');
80
+ if (outcome.recovery.mode === 'hold')
81
+ return outcome;
82
+ const owner = outcome.recovery.form || root?.id || id;
83
+ closeFormInstance(cargo, owner, false);
84
+ return { outcome: 'resolved', reason: 'request_cancelled', recovery: { version: 1, mode: 'none', reason: 'request_cancelled' } };
85
+ }
@@ -83,7 +83,7 @@ export function formPreparation(cargo: any, id: any, input: any): {
83
83
  export function queueFormReadings(cargo: any, hits?: any[]): boolean;
84
84
  export function pendingFormReadings(cargo: any, id: any): any[];
85
85
  export function formWorkLimit(cargo: any, id: any): number;
86
- export function applyFormValidation(cargo: any, id: any, result: any): "failed" | "valid" | "retry";
86
+ export function applyFormValidation(cargo: any, id: any, result: any): "retry" | "failed" | "valid";
87
87
  /** Invalidation is transitive and independent of declaration order. */
88
88
  export function invalidateFormInputs(cargo: any, id: any, changed: any, preserve?: any[], preserveNodes?: any[]): any[];
89
89
  /** An intentional retry resets the named inputs as well as all of their dependent state. Unknown actions stay held. */
@@ -92,8 +92,9 @@ export function resetFormInputs(cargo: any, id: any, names?: any[]): boolean;
92
92
  export function acceptFormReadings(cargo: any, hits: any, additionalCandidates?: any[]): boolean;
93
93
  /** Resolve the outermost stale opted-in context through actual active ownership, without mutation.
94
94
  * An unflagged wrapper must not hide an ancestor whose owner accepted a different field value.
95
+ * Optional pure ownerWork schedules owned pending work (such as input consent) before the context re-asks.
95
96
  */
96
- export function formParentResume(cargo: any, id: any, explicit?: boolean): {
97
+ export function formParentResume(cargo: any, id: any, explicit?: boolean, ownerWork?: null): {
97
98
  owner: any;
98
99
  child: any;
99
100
  } | null;
@@ -1 +1 @@
1
- {"version":3,"file":"form-state.d.ts","sourceRoot":"","sources":["../../src/helpers/form-state.js"],"names":[],"mappings":"AAOA,qDAKC;AAED,oDAEC;AAED,qFAAqF;AACrF,oEA2BC;AAuCD,2FAEC;AACD,8FAcC;AACD,2DAOC;AACD,uEAuCC;AAED,kGAAkG;AAClG,2GAOC;AACD,0HAA0H;AAC1H,uEAwBC;AACD,8HAA8H;AAC9H;;;;;EAWC;AACD,uGAAuG;AACvG;;;;;;;;;;;QAgCC;AAED,0FAA0F;AAC1F;;;SAIC;AACD,gGAAgG;AAChG;;;;;;;;;;;EAQC;AAED,sGAAsG;AACtG,2DAIC;AACD;;;GAGG;AACH;;;;;;;SAkBC;AAED,2FAA2F;AAC3F,oGAIC;AACD,gFA4BC;AAED,2GAA2G;AAC3G;;;EASC;AACD,mEAoBC;AACD,mEAGC;AACD,sEAUC;AACD,+EAEC;AACD,qFASC;AACD,oGAoCC;AACD;;;SAKC;AACD,qEAGC;AACD,gEAgBC;AACD,2DAQC;AACD,oGAUC;AAED,uEAAuE;AACvE,wHA+BC;AAED,uHAAuH;AACvH,6EAaC;AACD,mHAAmH;AACnH,iGA4CC;AACD;;GAEG;AACH;;;SAcC;AACD,+EASC;AACD,8EAeC;AA5kBM,8CAAmE"}
1
+ {"version":3,"file":"form-state.d.ts","sourceRoot":"","sources":["../../src/helpers/form-state.js"],"names":[],"mappings":"AAQA,qDAKC;AAED,oDAEC;AAED,qFAAqF;AACrF,oEA4BC;AAuCD,2FAEC;AACD,8FAcC;AACD,2DAOC;AACD,uEAuCC;AAED,kGAAkG;AAClG,2GAOC;AACD,0HAA0H;AAC1H,uEAwBC;AACD,8HAA8H;AAC9H;;;;;EAWC;AACD,uGAAuG;AACvG;;;;;;;;;;;QAgCC;AAED,0FAA0F;AAC1F;;;SAIC;AACD,gGAAgG;AAChG;;;;;;;;;;;EAQC;AAED,sGAAsG;AACtG,2DAIC;AACD;;;GAGG;AACH;;;;;;;SAkBC;AAED,2FAA2F;AAC3F,oGAIC;AACD,gFA4BC;AAED,2GAA2G;AAC3G;;;EASC;AACD,mEAoBC;AACD,mEAGC;AACD,sEAUC;AACD,+EAEC;AAoCD,qFAYC;AACD,oGAqCC;AACD;;;SAKC;AACD,qEAGC;AACD,gEAgBC;AACD,2DAQC;AACD,oGAUC;AAED,uEAAuE;AACvE,wHA+BC;AAED,uHAAuH;AACvH,6EAaC;AACD,mHAAmH;AACnH,iGAsDC;AACD;;;GAGG;AACH;;;SAcC;AACD,+EASC;AACD,8EAeC;AA/nBM,8CAAmE"}