jsfe 1.7.8 → 1.7.9
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.
- package/dist/forms/authoring.d.ts +10 -0
- package/dist/forms/authoring.d.ts.map +1 -0
- package/dist/forms/authoring.js +109 -0
- package/dist/forms/choice-flow.js +2 -2
- package/dist/forms/contracts.d.ts +7 -3
- package/dist/forms/contracts.d.ts.map +1 -1
- package/dist/forms/contracts.js +40 -18
- package/dist/forms/flows.d.ts.map +1 -1
- package/dist/forms/flows.js +36 -39
- package/dist/forms/index.d.ts +2 -0
- package/dist/forms/index.js +3 -1
- package/dist/forms/inspection.d.ts +12 -0
- package/dist/forms/inspection.d.ts.map +1 -0
- package/dist/forms/inspection.js +120 -0
- package/dist/helpers/contextual-response.d.ts +3 -0
- package/dist/helpers/contextual-response.d.ts.map +1 -1
- package/dist/helpers/contextual-response.js +7 -0
- package/dist/helpers/form-state.d.ts +1 -1
- package/dist/helpers/form-state.d.ts.map +1 -1
- package/dist/helpers/form-state.js +7 -5
- package/dist/helpers/index.d.ts +5 -5
- package/dist/helpers/index.d.ts.map +1 -1
- package/dist/helpers/index.js +3 -4
- package/dist/helpers/match-inputs.d.ts.map +1 -1
- package/dist/helpers/match-inputs.js +7 -35
- package/dist/helpers/money.d.ts +5 -3
- package/dist/helpers/money.d.ts.map +1 -1
- package/dist/helpers/money.js +25 -10
- package/dist/host/capabilities.d.ts.map +1 -1
- package/dist/host/capabilities.js +1 -2
- package/dist/index.d.ts +2 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -49
- package/dist/runtime-identity.js +1 -1
- package/docs/copilot-reference.md +1 -1
- package/docs/development-release.md +8 -0
- package/docs/forms.md +59 -21
- package/package.json +1 -1
- package/dist/helpers/semantic-input-prompt.d.ts +0 -2
- package/dist/helpers/semantic-input-prompt.d.ts.map +0 -1
- package/dist/helpers/semantic-input-prompt.js +0 -153
- package/dist/helpers/semantic-input.d.ts +0 -28
- package/dist/helpers/semantic-input.d.ts.map +0 -1
- package/dist/helpers/semantic-input.js +0 -47
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { nextFormInput, formValuesEqual } from '../helpers/form-state.js';
|
|
2
|
+
import { actionConfirmationValid } from '../helpers/form-actions.js';
|
|
3
|
+
const components = { collector: 'Form', provider: 'Provider', performer: 'Performer', worker: 'Worker', gate: 'Worker', router: 'Worker' };
|
|
4
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
5
|
+
const framesOf = session => (Array.isArray(session?.flowStacks) ? session.flowStacks : []).flat().filter(object);
|
|
6
|
+
/** Explain existing state; this neither authorizes an action nor records an event history.
|
|
7
|
+
* Values, request bodies, caller words and rendered questions are intentionally omitted.
|
|
8
|
+
* `previous` adds only observable field changes and invalidated confirmations; it cannot
|
|
9
|
+
* reconstruct intermediate events between the two snapshots.
|
|
10
|
+
*/
|
|
11
|
+
export function explainSession(session, { flows = [], previous } = {}) {
|
|
12
|
+
if (!object(session))
|
|
13
|
+
throw new TypeError('explainSession requires a session snapshot');
|
|
14
|
+
if (!Array.isArray(flows))
|
|
15
|
+
throw new TypeError('explainSession flows must be an array');
|
|
16
|
+
const registry = new Map(flows.filter(object).map(flow => [flow.id, flow]));
|
|
17
|
+
const cargo = object(session.cargo) ? session.cargo : {};
|
|
18
|
+
const forms = object(cargo.forms) ? cargo.forms : {};
|
|
19
|
+
const frames = framesOf(session), entries = [];
|
|
20
|
+
const activeIds = new Set(frames.flatMap(frame => [frame.variables?.form_instance, frame.variables?.form, frame.variables?.rf_form]).filter(id => typeof id === 'string'));
|
|
21
|
+
let held = !!session.continuationSafetyHold, uncertain = false, collecting = false, confirming = false;
|
|
22
|
+
const entry = (kind, message, source = {}) => entries.push({ kind, message, component: components[registry.get(source.flowId)?.variables?.contract?.value?.role] || 'Unknown', ...source });
|
|
23
|
+
const actions = new Map();
|
|
24
|
+
const action = (record, source) => {
|
|
25
|
+
if (!object(record))
|
|
26
|
+
return;
|
|
27
|
+
const identity = record.key || record;
|
|
28
|
+
const priority = ['attempted', 'unknown'].includes(record.status) || record.result?.status === 'unknown' ? 3 : record.status === 'completed' ? 2 : record.status === 'prepared' ? 1 : 0;
|
|
29
|
+
if (priority === 3)
|
|
30
|
+
held = true;
|
|
31
|
+
const previous = actions.get(identity);
|
|
32
|
+
// A duplicate key is not proof that both sources agree. Keep its most conservative
|
|
33
|
+
// evidence independently of traversal order, including journal/form contradictions.
|
|
34
|
+
if (priority && (!previous || priority > previous.priority))
|
|
35
|
+
actions.set(identity, { priority, source: source.flowId ? source : previous?.source || source });
|
|
36
|
+
};
|
|
37
|
+
if (session.continuationSafetyHold)
|
|
38
|
+
entry('continuation_held', 'An earlier action or incompatible continuation requires review before continuing.');
|
|
39
|
+
for (const [id, state] of Object.entries(forms)) {
|
|
40
|
+
if (!object(state)) {
|
|
41
|
+
uncertain = true;
|
|
42
|
+
entry('unavailable', 'This form state cannot be inspected.', { form: id });
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const source = { flowId: state.definition, form: id }, active = activeIds.has(id), before = previous?.cargo?.forms?.[id];
|
|
46
|
+
if (object(before)) {
|
|
47
|
+
const names = new Set([...Object.keys(before.values || {}), ...Object.keys(state.values || {})]);
|
|
48
|
+
for (const input of names)
|
|
49
|
+
if (!formValuesEqual(before.values?.[input], state.values?.[input]))
|
|
50
|
+
entry('input_changed', 'The field changed; its current value is withheld from the explanation.', { ...source, input });
|
|
51
|
+
if (before.confirmation && !formValuesEqual(before.confirmation, state.confirmation))
|
|
52
|
+
entry(state.confirmation ? 'confirmation_changed' : 'confirmation_invalidated', state.confirmation ? 'A different confirmation is now recorded; it must match the current proposal.' : 'The earlier confirmation no longer applies. A fresh confirmation is required for the revised proposal.', source);
|
|
53
|
+
}
|
|
54
|
+
let next;
|
|
55
|
+
try {
|
|
56
|
+
if (!Array.isArray(state.specs) || !object(state.values))
|
|
57
|
+
throw new TypeError('Incomplete snapshot');
|
|
58
|
+
next = nextFormInput(state, cargo);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
uncertain = true;
|
|
62
|
+
entry('unavailable', 'Required input state cannot be determined from this snapshot.', source);
|
|
63
|
+
}
|
|
64
|
+
if (next) {
|
|
65
|
+
const blocked = next === '__blocked__';
|
|
66
|
+
entry(blocked ? 'input_blocked' : 'input_missing', blocked ? 'Required inputs are waiting on their prerequisites.' : active ? 'Collecting this required input.' : 'This saved form still needs this input.', { ...source, ...(!blocked ? { input: next } : {}), active });
|
|
67
|
+
if (active)
|
|
68
|
+
collecting = true;
|
|
69
|
+
}
|
|
70
|
+
const proposal = state.proposal;
|
|
71
|
+
if (proposal?.status === 'prepared' && next === '') {
|
|
72
|
+
const valid = actionConfirmationValid(cargo, id, proposal);
|
|
73
|
+
entry(valid ? 'confirmation_recorded' : 'confirmation_needed', valid ? 'Confirmation matches the current proposal; other execution guards still apply.' : 'Waiting for confirmation of the current proposal.', { ...source, active });
|
|
74
|
+
if (active && !valid)
|
|
75
|
+
confirming = true;
|
|
76
|
+
}
|
|
77
|
+
else if (state.confirmation && next) {
|
|
78
|
+
entry('confirmation_stale', 'A recorded confirmation cannot authorize an incomplete form.', source);
|
|
79
|
+
}
|
|
80
|
+
action(state.proposal, source);
|
|
81
|
+
for (const record of Object.values(state.actions || {}))
|
|
82
|
+
action(record, source);
|
|
83
|
+
for (const [input, proposal] of Object.entries(state.inputProposals || {}))
|
|
84
|
+
if (proposal && !proposal.committed && proposal.status === 'pending') {
|
|
85
|
+
entry('input_confirmation_needed', 'A proposed field value is waiting for confirmation.', { ...source, input, active });
|
|
86
|
+
if (active)
|
|
87
|
+
confirming = true;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
for (const record of Object.values(cargo.actionJournal || {}))
|
|
91
|
+
action(record, {});
|
|
92
|
+
for (const { priority, source } of actions.values()) {
|
|
93
|
+
if (priority === 3)
|
|
94
|
+
entry('action_held', 'An action has been attempted and its result is not confirmed. Automatic repetition is blocked.', source);
|
|
95
|
+
else if (priority === 2)
|
|
96
|
+
entry('action_completed', 'An action attempt has a recorded result. This does not authorize another attempt.', source);
|
|
97
|
+
else
|
|
98
|
+
entry('action_prepared', 'An action proposal is prepared; execution still requires its guards.', source);
|
|
99
|
+
}
|
|
100
|
+
// Completed forms may already be cleared. The generic last result remains evidence of
|
|
101
|
+
// its recorded outcome, but carries no authority or reliable component identity by itself.
|
|
102
|
+
const lastResult = cargo.actionResult;
|
|
103
|
+
const resultMessages = { ok: 'The most recent action result is recorded as successful.', failed: 'The most recent action result is recorded as failed.', unknown: 'The most recent action result is unconfirmed; consult the current action hold.', not_applicable: 'The most recent performer recorded that no action was applicable.' };
|
|
104
|
+
if (object(lastResult) && Object.hasOwn(resultMessages, lastResult.status))
|
|
105
|
+
entry('action_result', resultMessages[lastResult.status]);
|
|
106
|
+
const handoff = session.lastTurnDispatch;
|
|
107
|
+
const handedOff = handoff?.matchedFlow === null && frames.length === 0;
|
|
108
|
+
if (handedOff)
|
|
109
|
+
entry('handoff', 'DISPATCH yielded this turn to the host for contextual interpretation.', { flowId: registry.has(handoff.fromFlow) ? handoff.fromFlow : [...registry.values()].find(flow => flow.name === handoff.fromFlow)?.id });
|
|
110
|
+
const current = frames.at(-1);
|
|
111
|
+
if (current) {
|
|
112
|
+
const step = current.flowStepsStack?.at(-1);
|
|
113
|
+
const reversed = [...frames].reverse();
|
|
114
|
+
const author = reversed.find(frame => ['Form', 'Provider', 'Performer'].includes(registry.get(frame.flowId)?.metadata?.authoring?.component))
|
|
115
|
+
|| reversed.find(frame => registry.get(frame.flowId)?.metadata?.authoring?.component)
|
|
116
|
+
|| reversed.find(frame => { const definition = registry.get(frame.flowId); const role = definition?.variables?.contract?.value?.role; return ['provider', 'performer'].includes(role) || role === 'collector' && (definition?.primary || definition?.metadata?.formProtocol === 2); }) || current;
|
|
117
|
+
entry('current_step', 'Current execution location.', { flowId: author.flowId, ...(current.flowId !== author.flowId ? { workerFlowId: current.flowId } : {}), ...(step?.id ? { step: step.id } : {}) });
|
|
118
|
+
}
|
|
119
|
+
return { status: held ? 'held' : uncertain ? 'unknown' : handedOff ? 'handed_off' : confirming ? 'confirmation' : collecting ? 'collecting' : frames.length ? 'active' : 'idle', entries };
|
|
120
|
+
}
|
|
@@ -4,7 +4,10 @@ export function validateContextualResponseStep(step: any, flow: any): {
|
|
|
4
4
|
variable: any;
|
|
5
5
|
} | null | undefined;
|
|
6
6
|
export function contextualResponseRuntimeSteps(id: any, steps: any, requirements?: any[]): any;
|
|
7
|
+
/** A normal extraction description for an open-ended FORM answer, using contextual DISPATCH. */
|
|
8
|
+
export function validateFormResponse(response: any): any;
|
|
7
9
|
/** Explicit typed contextual responses. No engine state, transport, or host permissions. */
|
|
8
10
|
export const CONTEXTUAL_RESPONSES_REQUIREMENT: "jsfe:contextual-responses:v1";
|
|
9
11
|
export function contextualResponseProtocol(): number;
|
|
12
|
+
export function hasFormResponse(inputs: any): any;
|
|
10
13
|
//# sourceMappingURL=contextual-response.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contextual-response.d.ts","sourceRoot":"","sources":["../../src/helpers/contextual-response.js"],"names":[],"mappings":"AAMA,2GAA2G;AAC3G;;;qBAiBC;AACD,+FAIC;
|
|
1
|
+
{"version":3,"file":"contextual-response.d.ts","sourceRoot":"","sources":["../../src/helpers/contextual-response.js"],"names":[],"mappings":"AAMA,2GAA2G;AAC3G;;;qBAiBC;AACD,+FAIC;AAED,gGAAgG;AAChG,yDAGC;AAnCD,4FAA4F;AAC5F,+CAAgD,8BAA8B,CAAC;AACxE,qDAA0C;AAkC1C,kDAA8J"}
|
|
@@ -46,3 +46,10 @@ export function contextualResponseRuntimeSteps(id, steps, requirements = []) {
|
|
|
46
46
|
const guard = { id: id + '_contextual_response_protocol', type: 'SET', variable: 'noop', value: 'contextualResponseProtocol() === 1', requireTrue: true };
|
|
47
47
|
return steps[0]?.type === 'SET' && steps[0]?.value === guard.value && steps[0]?.requireTrue === true ? steps : [guard, ...steps];
|
|
48
48
|
}
|
|
49
|
+
/** A normal extraction description for an open-ended FORM answer, using contextual DISPATCH. */
|
|
50
|
+
export function validateFormResponse(response) {
|
|
51
|
+
if (!response || typeof response !== 'object' || Array.isArray(response) || Object.keys(response).some(k => k !== 'description') || typeof response.description !== 'string' || !response.description.trim())
|
|
52
|
+
fail('FORM response requires a nonempty description only');
|
|
53
|
+
return structuredClone(response);
|
|
54
|
+
}
|
|
55
|
+
export const hasFormResponse = inputs => (inputs || []).some(input => input.response !== undefined || hasFormResponse(input.any_of) || hasFormResponse(input.schema?.inputs));
|
|
@@ -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): "
|
|
86
|
+
export function applyFormValidation(cargo: any, id: any, result: any): "failed" | "valid" | "retry";
|
|
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. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-state.d.ts","sourceRoot":"","sources":["../../src/helpers/form-state.js"],"names":[],"mappings":"AAQA,qDAKC;AAED,oDAEC;AAED,qFAAqF;AACrF,
|
|
1
|
+
{"version":3,"file":"form-state.d.ts","sourceRoot":"","sources":["../../src/helpers/form-state.js"],"names":[],"mappings":"AAQA,qDAKC;AAED,oDAEC;AAED,qFAAqF;AACrF,oEA6BC;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;AAhoBM,8CAAmE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { validateFormResponse } from './contextual-response.js';
|
|
2
2
|
import { validateFormProposalPolicy } from './proposal-contract.js';
|
|
3
3
|
/** Shared FORM semantics. Pure readers plus explicit mutations of the supplied session container; no host I/O. */
|
|
4
4
|
import { readInputProfile } from './match-inputs.js';
|
|
@@ -37,10 +37,12 @@ export function resolveFormInputs(inputs, presets = {}) {
|
|
|
37
37
|
validateMoneyOptions(input.profile.money);
|
|
38
38
|
}
|
|
39
39
|
validateFormExhaustion(input.on_exhausted);
|
|
40
|
-
if (input.meaning !== undefined)
|
|
40
|
+
if (input.meaning !== undefined)
|
|
41
|
+
throw new Error('FORM meaning is retired; use a contextual response description');
|
|
42
|
+
if (input.response !== undefined) {
|
|
41
43
|
if (!input.profile || input.form || input.any_of || input.bind)
|
|
42
|
-
throw new Error('FORM
|
|
43
|
-
|
|
44
|
+
throw new Error('FORM response requires a readable leaf input');
|
|
45
|
+
validateFormResponse(input.response);
|
|
44
46
|
}
|
|
45
47
|
if (input.proposal !== undefined) {
|
|
46
48
|
if (!input.profile || input.form || input.any_of || input.bind)
|
|
@@ -204,7 +206,7 @@ export function enrichFormMatches(matches, chain, form, names = [], asked = '')
|
|
|
204
206
|
const enrich = h => {
|
|
205
207
|
const spec = chain.find(c => c.form === h.form && c.name === h.name) || {};
|
|
206
208
|
return { ...h, label: h.option_label || spec.label || h.name, label_es: h.option_label_es || spec.label_es || spec.label || h.name,
|
|
207
|
-
validator: spec.validator || '', ...(spec.
|
|
209
|
+
validator: spec.validator || '', ...(spec.response ? { response: spec.response } : {}), after: spec.after || '', validate_always: spec.validate_always === true, ...(spec.activation ? { activation: spec.activation } : {}), pii: spec.pii === true, current: h.form === form && names.includes(h.name), asked };
|
|
208
210
|
};
|
|
209
211
|
return { ...matches, hits: matches.hits.map(enrich), ambiguous: matches.ambiguous.map(enrich), remaining: (matches.remaining || []).map(group => group.map(enrich)) };
|
|
210
212
|
}
|
package/dist/helpers/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export namespace STANDARD_FUNCTIONS {
|
|
2
2
|
export { continuationSafetyProtocol };
|
|
3
|
-
export { semanticInputValidationProtocol };
|
|
4
|
-
export { validateInputMeaning };
|
|
5
3
|
export { cancelFormTask };
|
|
6
4
|
export { contextualResponseProtocol };
|
|
5
|
+
export { validateFormResponse };
|
|
6
|
+
export { hasFormResponse };
|
|
7
7
|
export { formProposalPolicy };
|
|
8
8
|
export { stageFormProposal };
|
|
9
9
|
export { nextFormProposal };
|
|
@@ -114,10 +114,10 @@ export namespace STANDARD_FUNCTIONS {
|
|
|
114
114
|
export { textWithUrlToSpeech };
|
|
115
115
|
}
|
|
116
116
|
import { continuationSafetyProtocol } from '../forms/continuation-safety.js';
|
|
117
|
-
import { semanticInputValidationProtocol } from './semantic-input.js';
|
|
118
|
-
import { validateInputMeaning } from './semantic-input.js';
|
|
119
117
|
import { cancelFormTask } from './form-conversation.js';
|
|
120
118
|
import { contextualResponseProtocol } from './contextual-response.js';
|
|
119
|
+
import { validateFormResponse } from './contextual-response.js';
|
|
120
|
+
import { hasFormResponse } from './contextual-response.js';
|
|
121
121
|
import { formProposalPolicy } from './form-proposals.js';
|
|
122
122
|
import { stageFormProposal } from './form-proposals.js';
|
|
123
123
|
import { nextFormProposal } from './form-proposals.js';
|
|
@@ -231,5 +231,5 @@ import { validatePhone } from './validators.js';
|
|
|
231
231
|
import { validateEmail } from './validators.js';
|
|
232
232
|
import { urlToSpeech } from './url-speech.js';
|
|
233
233
|
import { textWithUrlToSpeech } from './url-speech.js';
|
|
234
|
-
export { continuationSafetyProtocol,
|
|
234
|
+
export { continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse, formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation, formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor, clearFormMisses, missFormInput, formInputPrompt, consumeFormFeedback, formConversationOutcome, readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, matchesChoice, ANSWER_WORDS, CONFIRM_WORDS, isAnswer, isAgentRequest, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice, readEmail, readPhone, readInternationalPhone, readIdentifier, last4, maskEmail, callerTextNumber, textDestination, callerIsInternational, normalizeAndFindCapture, anythingElse, goodbye, sayName, dateToWords, amountToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readInputProfile, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance, checkOtp, maskDestination, validateOTP, OTP_EXPIRY_MS, validateDigits, validatePhone, validateEmail, urlToSpeech, textWithUrlToSpeech };
|
|
235
235
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/helpers/index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAAyC,iCAAiC;
|
|
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"}
|
package/dist/helpers/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { continuationSafetyProtocol } from '../forms/continuation-safety.js';
|
|
2
|
-
import {
|
|
3
|
-
import { contextualResponseProtocol } from './contextual-response.js';
|
|
2
|
+
import { contextualResponseProtocol, validateFormResponse, hasFormResponse } from './contextual-response.js';
|
|
4
3
|
import { formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation } from './form-proposals.js';
|
|
5
4
|
import { formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor } from './proposal-contract.js';
|
|
6
5
|
import { cancelFormTask, clearFormMisses, missFormInput, formInputPrompt, consumeFormFeedback, formConversationOutcome } from './form-conversation.js';
|
|
@@ -35,10 +34,10 @@ import { resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, fo
|
|
|
35
34
|
import { checkOtp, maskDestination, validateOTP, OTP_EXPIRY_MS } from './otp-check.js';
|
|
36
35
|
import { validateDigits, validatePhone, validateEmail } from './validators.js';
|
|
37
36
|
import { urlToSpeech, textWithUrlToSpeech } from './url-speech.js';
|
|
38
|
-
export { continuationSafetyProtocol,
|
|
37
|
+
export { continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse, formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation, formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor, clearFormMisses, missFormInput, formInputPrompt, consumeFormFeedback, formConversationOutcome, readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, matchesChoice, ANSWER_WORDS, CONFIRM_WORDS, isAnswer, isAgentRequest, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice, readEmail, readPhone, readInternationalPhone, readIdentifier, last4, maskEmail, callerTextNumber, textDestination, callerIsInternational, normalizeAndFindCapture, anythingElse, goodbye, sayName, dateToWords, amountToSpeech, validateCardNumber, validateExpiration, consumeActionReceipt, authorizeFormActionRetry, formSignature, selectFormAction, confirmFormRevision, prepareFormAction, actionConfirmationValid, beginFormAction, finishFormAction, actionGateVerified, sourceNeedsLoad, beginSourceRefresh, completeSourceRefresh, pickProviderQuestion, matchInputs, readFormAnswer, readInputProfile, resolveFormInputs, formInputApplies, formInputFilled, nextFormInput, formInputChain, openFormInstance, validateFormIncompleteOutcome, formIncompleteOutcome, validateFormExhaustion, exhaustFormInput, formInitialReadings, orderFormReadings, proposedFormValues, applyFormValidation, formReadingDependencies, exclusiveFormReadings, enrichFormMatches, expandFormActivations, settleFormActivations, rememberFormArguments, resetFormInputs, hasFormValue, formPath, formValuesEqual, formReadingReady, formReadingRelevant, formPreparation, queueFormReadings, pendingFormReadings, formWorkLimit, rejectFormReadings, invalidateFormInputs, acceptFormReadings, formInstanceApplies, formParentResume, closeFormInstance, checkOtp, maskDestination, validateOTP, OTP_EXPIRY_MS, validateDigits, validatePhone, validateEmail, urlToSpeech, textWithUrlToSpeech, };
|
|
39
38
|
/** The functions flows call by name, ready to spread into a host's approved functions. */
|
|
40
39
|
export const STANDARD_FUNCTIONS = {
|
|
41
|
-
continuationSafetyProtocol,
|
|
40
|
+
continuationSafetyProtocol, cancelFormTask, contextualResponseProtocol, validateFormResponse, hasFormResponse,
|
|
42
41
|
formProposalPolicy, stageFormProposal, nextFormProposal, formProposalReadings, bindFormProposal, decideFormProposal, commitFormProposals, settleFormProposalValidation, formProposalProtocol, validateFormProposalPolicy, validateFormProposalDescriptor, formProposalDescriptor,
|
|
43
42
|
clearFormMisses, missFormInput, formInputPrompt, consumeFormFeedback, formConversationOutcome,
|
|
44
43
|
readMoneyAmount, isMoneyAmount, moneyIntentAllows, isPastPaymentStatement, isPartialMoneyAnswer, validateMoneyOptions, takeChoiceOffer, matchesChoice, isAnswer, isAgentRequest, isOtherRequest, isSpelledFragment, isAmountAnswer, amountInAnswer, pickChoice,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"match-inputs.d.ts","sourceRoot":"","sources":["../../src/helpers/match-inputs.js"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"match-inputs.d.ts","sourceRoot":"","sources":["../../src/helpers/match-inputs.js"],"names":[],"mappings":"AAoFA;;;GAGG;AACH,sFAgGC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH;mHACmH;AACnH;;;;;EAeC;AACD;;;;;;EAkHC"}
|
|
@@ -12,7 +12,7 @@ import { matchesChoice } from './matches-choice.js';
|
|
|
12
12
|
import { pickChoice, amountInAnswer, isAmountAnswer } from './answer.js';
|
|
13
13
|
import { readEmail, readPhone, readInternationalPhone, readIdentifier } from './contact.js';
|
|
14
14
|
import { readSpokenMoney } from './spoken-money.js';
|
|
15
|
-
import { readMoneyAmount,
|
|
15
|
+
import { readMoneyAmount, isPartialMoneyAnswer } from './money.js';
|
|
16
16
|
import { pickProviderQuestion } from './form-sources.js';
|
|
17
17
|
/** The answer as said: jsfe stores user input escaped (don\'t). */
|
|
18
18
|
function unescape(answer) {
|
|
@@ -77,18 +77,6 @@ function emailSpans(raw, value) {
|
|
|
77
77
|
}
|
|
78
78
|
return [[0, raw.length]];
|
|
79
79
|
}
|
|
80
|
-
/** Explicitly revise a declared choice, rather than mentioning it inside a requested narrative.
|
|
81
|
-
* The remaining correction clause must itself be a whole declared choice; a cue alone is not authority.
|
|
82
|
-
*/
|
|
83
|
-
function choiceCorrection(raw, choices, value) {
|
|
84
|
-
const prefix = /^\s*(?:(?:please|por favor)\s+)?(?:actually|instead|rather|i (?:mean|meant)|make it|switch to|change (?:it |the service |my service )?to|en realidad|mejor|quise decir|quiero decir|cambi(?:a|e|é|ar) (?:el servicio )?a)\s*[,;:]?\s+/iu;
|
|
85
|
-
const suffix = /\s+(?:instead|en su lugar)\s*[.!]?\s*$/iu;
|
|
86
|
-
const clauses = [raw, ...raw.split(/[,;\n]/)];
|
|
87
|
-
return clauses.some(clause => {
|
|
88
|
-
const replaced = clause.replace(prefix, '').replace(suffix, '');
|
|
89
|
-
return replaced !== clause && pickChoice(replaced.split(/[,;\n]/)[0], choices, false) === value;
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
80
|
/** Remove independently spent evidence while leaving the original narrative value intact. */
|
|
93
81
|
function unclaimedSpans(raw, readings) {
|
|
94
82
|
let spans = [[0, raw.length]];
|
|
@@ -143,14 +131,6 @@ export function readInputProfile(profile, answer, isCurrent = true) {
|
|
|
143
131
|
if (isPartialMoneyAnswer(raw))
|
|
144
132
|
return { value: raw, incompleteMoney: true, spans: [[0, raw.length]], evidence: ['partial-money'] };
|
|
145
133
|
const read = money ? text => readMoneyAmount(text, money) : amountInAnswer;
|
|
146
|
-
// A historical report belongs to its task router, not an amount correction or refusal proposal.
|
|
147
|
-
if (money?.intent === 'payment' && isPastPaymentStatement(raw))
|
|
148
|
-
return null;
|
|
149
|
-
const refused = !!money && money.intent === 'payment' && !moneyIntentAllows(raw, 'payment');
|
|
150
|
-
// A refusal is an uncommittable validation candidate, never a numeric correction. A declared
|
|
151
|
-
// validator may route it to recovery; the common batch always withholds acceptance.
|
|
152
|
-
if (refused)
|
|
153
|
-
return Number.isFinite(readMoneyAmount(raw, { ...money, intent: undefined })) ? { value: raw, refused: true, spans: [[0, raw.length]], evidence: ['money-intent'] } : null;
|
|
154
134
|
const n = (profile.marked === 'out_of_order' ? !isCurrent : profile.marked) ? (isAmountAnswer(raw) ? read(raw) : NaN) : read(raw);
|
|
155
135
|
const inRange = !isNaN(n) && (profile.min === undefined || n >= Number(profile.min)) && (profile.max === undefined || n <= Number(profile.max));
|
|
156
136
|
if (inRange) {
|
|
@@ -295,14 +275,6 @@ export function matchInputs(answer, candidates, current, choiceKey) {
|
|
|
295
275
|
for (const c of list) {
|
|
296
276
|
const profile = narrativeCurrent && c.profile.kind === 'email' ? { ...c.profile, literal: true } : c.profile;
|
|
297
277
|
let r = readInputProfile(profile, raw, isCur(c));
|
|
298
|
-
// An opted-in narrative can still receive an explicit correction whose declared word
|
|
299
|
-
// is otherwise a strict acknowledgement (for example Spanish `seguro`). Preserve the
|
|
300
|
-
// noncurrent keypad/current-only rules when recognizing that correction clause.
|
|
301
|
-
if (!r && !isCur(c) && c.profile.kind === 'choice' && narrativeCurrent) {
|
|
302
|
-
const corrected = (c.profile.choices || []).filter(choice => choice.current_only !== true).map(choice => ({ ...choice, exact: true, words: (choice.words || []).filter(word => c.profile.numeric_values === true || !/^[\d*#]$/.test(String(word).trim())) })).filter(choice => choiceCorrection(raw, [choice], choice.key)).map(choice => ({ value: choice.key, spans: choiceSpans(raw, choice.words) }));
|
|
303
|
-
if (corrected.length)
|
|
304
|
-
r = corrected.length === 1 ? corrected[0] : { alternatives: corrected };
|
|
305
|
-
}
|
|
306
278
|
// A semantic choice supplied by ask-choice (e.g. spoken keypad keys) is a reading, not an early return.
|
|
307
279
|
if (!r && c === own && choiceKey && c.profile.kind === 'choice' && (c.profile.choices || []).some(x => x.key === choiceKey)) {
|
|
308
280
|
r = { ...(r || {}), value: choiceKey, spans: r?.spans?.length ? r.spans : [[0, raw.length]] };
|
|
@@ -316,7 +288,7 @@ export function matchInputs(answer, candidates, current, choiceKey) {
|
|
|
316
288
|
const isChoice = !isCur(c) && c.profile.kind === 'choice';
|
|
317
289
|
const wholeOptions = isChoice ? (c.profile.choices || []).filter(choice => choice.key === option.value).map(choice => ({ ...choice, exact: true })) : [];
|
|
318
290
|
const wholeChoice = isChoice && [raw, raw.replace(/\d(?:[\s.-]?\d)*/g, run => run.replace(/\D/g, ''))].some(text => pickChoice(text, wholeOptions, false) === option.value);
|
|
319
|
-
readings.push({ form: c.form, name: c.name, value: option.value, ...(option.refused === true ? { refused: true } : {}), ...(option.incompleteMoney === true ? { incompleteMoney: true } : {}), known, repeatedChoice, wholeChoice, choice: isChoice,
|
|
291
|
+
readings.push({ form: c.form, name: c.name, value: option.value, ...(option.refused === true ? { refused: true } : {}), ...(option.incompleteMoney === true ? { incompleteMoney: true } : {}), known, repeatedChoice, wholeChoice, choice: isChoice, narrative: isCur(c) && ['text', 'choice'].includes(c.profile.kind) && c.profile.narrative === true, resetOn: Array.isArray(c.reset_on) ? c.reset_on : [], spans: option.spans, keypad: option.keypad === true, fallback: option.fallback === true,
|
|
320
292
|
...(r.alternatives ? { option_label: option.option_label, option_label_es: option.option_label_es } : {}), group: c.group, exclusive: c.exclusive === true, level: forms.indexOf(c.scope || c.form), current: isCur(c), confirm: Array.isArray(c.confirm_against) ? c.confirm_against : [] });
|
|
321
293
|
}
|
|
322
294
|
}
|
|
@@ -324,10 +296,10 @@ export function matchInputs(answer, candidates, current, choiceKey) {
|
|
|
324
296
|
const paired = (a, b) => a.confirm.indexOf(b.name) > -1 || b.confirm.indexOf(a.name) > -1;
|
|
325
297
|
// Narrative ownership protects ancestor choices and same-form choices that reset
|
|
326
298
|
// the requested field. Other sibling choices remain independent compound data. A current choice can carry narrative context too (e.g. a channel plus a
|
|
327
|
-
// complaint). Preserve declared
|
|
299
|
+
// complaint). Preserve whole declared choices and confirmation pairs, and leave all
|
|
328
300
|
// independently shaped non-choice fields available for compound collection.
|
|
329
301
|
const owners = readings.filter(reading => reading.current && reading.narrative);
|
|
330
|
-
readings = readings.filter(reading => !reading.choice || !owners.some(owner => (reading.level > owner.level || reading.form === owner.form && owner.resetOn.includes(reading.name)) && !reading.wholeChoice && !
|
|
302
|
+
readings = readings.filter(reading => !reading.choice || !owners.some(owner => (reading.level > owner.level || reading.form === owner.form && owner.resetOn.includes(reading.name)) && !reading.wholeChoice && !paired(owner, reading)));
|
|
331
303
|
const fieldConflict = (a, b) => a.form === b.form && (a.name === b.name && a.value !== b.value || a.exclusive && b.exclusive && a.group && a.group === b.group && a.name !== b.name);
|
|
332
304
|
const overlap = (a, b) => (a.spans || []).some(([s, e]) => (b.spans || []).some(([t, u]) => s < u && t < e));
|
|
333
305
|
const competes = (a, b) => fieldConflict(a, b) || overlap(a, b);
|
|
@@ -341,12 +313,12 @@ export function matchInputs(answer, candidates, current, choiceKey) {
|
|
|
341
313
|
const structured = readings.filter(reading => !reading.fallback);
|
|
342
314
|
const prose = unclaimedSpans(raw, structured);
|
|
343
315
|
if (prose.some(([a, b]) => /\p{L}/u.test(raw.slice(a, b)))) {
|
|
344
|
-
const independent = structured.filter(reading => (!reading.choice || reading.level === fallback.level && !reading.wholeChoice && !
|
|
316
|
+
const independent = structured.filter(reading => (!reading.choice || reading.level === fallback.level && !reading.wholeChoice && !fallback.resetOn.includes(reading.name)) && !fieldConflict(fallback, reading) && !paired(fallback, reading));
|
|
345
317
|
if (independent.length)
|
|
346
318
|
fallback.spans = unclaimedSpans(raw, independent);
|
|
347
319
|
}
|
|
348
320
|
}
|
|
349
|
-
const contextualChoice = (fallback, reading) => !paired(fallback, reading) && !reading.wholeChoice && (reading.repeatedChoice
|
|
321
|
+
const contextualChoice = (fallback, reading) => !paired(fallback, reading) && !reading.wholeChoice && (reading.repeatedChoice || fallback.narrative && reading.choice && (reading.level > fallback.level || reading.form === fallback.form && fallback.resetOn.includes(reading.name)));
|
|
350
322
|
const stronger = new Map(fallbacks.map(fallback => [fallback, readings.filter(reading => !reading.fallback && competes(fallback, reading) && !contextualChoice(fallback, reading))]));
|
|
351
323
|
const keptFallbacks = fallbacks.filter(fallback => !stronger.get(fallback).length || stronger.get(fallback).some(reading => paired(fallback, reading)));
|
|
352
324
|
const pairedFallbacks = new Set(keptFallbacks.filter(fallback => stronger.get(fallback).length));
|
|
@@ -368,7 +340,7 @@ export function matchInputs(answer, candidates, current, choiceKey) {
|
|
|
368
340
|
}
|
|
369
341
|
const groups = {};
|
|
370
342
|
effective.forEach((r, i) => { (groups[find(i)] = groups[find(i)] || []).push(r); });
|
|
371
|
-
const strip = ({ evidence, spans, keypad, fallback, repeatedChoice, wholeChoice, choice,
|
|
343
|
+
const strip = ({ evidence, spans, keypad, fallback, repeatedChoice, wholeChoice, choice, narrative, resetOn, level, group, exclusive, current: c, confirm, ...r }) => r;
|
|
372
344
|
const hits = [];
|
|
373
345
|
let ambiguous = [];
|
|
374
346
|
const remaining = [];
|
package/dist/helpers/money.d.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
/** A profile must declare its currency; currently only USD grammar is supported. No exchange-rate inference. */
|
|
2
2
|
export function validateMoneyOptions(options: any): any;
|
|
3
|
-
/**
|
|
3
|
+
/** Accept only a complete monetary answer or a simple explicit payment instruction.
|
|
4
|
+
* A false result makes no claim about intent, refusal, tense or the caller's next request. */
|
|
4
5
|
export function moneyIntentAllows(input: any, intent: any): boolean;
|
|
5
6
|
/** A cents-only continuation needs a complete amount; it is not an independent replacement. */
|
|
6
7
|
export function isPartialMoneyAnswer(input: any): boolean;
|
|
7
|
-
/**
|
|
8
|
+
/** Compatibility predicate for a whole short historical report, never a search through prose.
|
|
9
|
+
* Payment collectors do not use this to route or answer the caller; DISPATCH owns that decision. */
|
|
8
10
|
export function isPastPaymentStatement(input: any): boolean;
|
|
9
11
|
/** Number or NaN. currency is required; cardinals defaults false and intent is optional.
|
|
10
12
|
* Explicit foreign currencies, negative amounts and independent unequal readings fail closed.
|
|
11
|
-
*
|
|
13
|
+
* Payment intent accepts a bounded whole answer; unrelated prose is never mined for an amount or consent.
|
|
12
14
|
*/
|
|
13
15
|
export function readMoneyAmount(input: any, options: any): any;
|
|
14
16
|
/** True exactly when the opted-in reader returns a finite amount (bare digits included). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"money.d.ts","sourceRoot":"","sources":["../../src/helpers/money.js"],"names":[],"mappings":"AAIA,gHAAgH;AAChH,wDAGC;
|
|
1
|
+
{"version":3,"file":"money.d.ts","sourceRoot":"","sources":["../../src/helpers/money.js"],"names":[],"mappings":"AAIA,gHAAgH;AAChH,wDAGC;AAiBD;8FAC8F;AAC9F,oEAIC;AACD,+FAA+F;AAC/F,0DAEC;AACD;oGACoG;AACpG,4DAGC;AAWD;;;GAGG;AACH,+DAYC;AACD,4FAA4F;AAC5F,iEAAsG"}
|
package/dist/helpers/money.js
CHANGED
|
@@ -7,26 +7,41 @@ export function validateMoneyOptions(options) {
|
|
|
7
7
|
throw new Error('Money options require currency USD, optional boolean cardinals and optional payment intent');
|
|
8
8
|
return options;
|
|
9
9
|
}
|
|
10
|
-
|
|
10
|
+
// This is an input grammar, not a conversation classifier. Anything outside one complete
|
|
11
|
+
// monetary answer belongs to DISPATCH, including refusals, corrections with context and reports.
|
|
12
|
+
const NUMERIC_MONEY = /^(?:\$\s*)?(?:\d{1,3}(?:[,.]\d{3})+|\d+)(?:[.,]\d{1,2})?(?:\s*(?:dollars?|d[oó]lar(?:es)?|bucks?))?(?:\s*(?:and|con|y)\s*(?:un\s*)?\d{1,2}(?:\s*(?:cents?|centavos?))?)?$|^\d{1,2}\s*(?:cents?|centavos?)$/i;
|
|
13
|
+
const PAYMENT_PREFIX = /^(?:(?:i (?:want to|would like to|can|am able to|will) |i['’]d like to )?pay|(?:quiero |quisiera |puedo |s[ií] puedo |voy a )?(?:pagar|abonar)|(?:no,?\s+)?make it)\s*(?=\$|\d|[a-záéíóúüñ])/i;
|
|
14
|
+
const ACCOUNT_PREFIX = /^(?:(?:sub[ -]?account|subcuenta|cuenta)\s+\d{1,8}\s*,\s*)/i;
|
|
15
|
+
const DIGIT_WORD = '(?:zero|one|two|three|four|five|six|seven|eight|nine|cero|uno|dos|tres|cuatro|cinco|seis|siete|ocho|nueve)';
|
|
16
|
+
const CARD_SUFFIX = new RegExp('\\s+(?:with (?:the |my )?card(?: (?:ending(?: in)?|number))?|con (?:la |mi )?tarjeta(?: (?:que termina en|terminad[ao] en))?)\\s+(?:\\d(?:[ -]?\\d){3}|' + DIGIT_WORD + '(?: ' + DIGIT_WORD + '){3})$', 'i');
|
|
17
|
+
const ACCOUNT_SUFFIX = /\s+(?:(?:on|to) (?:sub[ -]?account|account)|(?:a|en) (?:la )?(?:subcuenta|cuenta))\s+\d{1,8}$/i;
|
|
18
|
+
function completeMoneyAnswer(input) {
|
|
19
|
+
let raw = String(input ?? '').replace(/\\(['"\\])/g, '$1').trim().replace(/^[¡!]+|[.!]+$/g, '').trim();
|
|
20
|
+
raw = raw.replace(/^(?:please|por favor)[, ]+/i, '').replace(/[, ]+(?:please|por favor)$/i, '').trim();
|
|
21
|
+
raw = raw.replace(PAYMENT_PREFIX, '').replace(ACCOUNT_PREFIX, '').replace(CARD_SUFFIX, '').replace(ACCOUNT_SUFFIX, '').trim();
|
|
22
|
+
if (NUMERIC_MONEY.test(raw))
|
|
23
|
+
return true;
|
|
24
|
+
const { readings, invalid } = scanSpokenMoney(raw);
|
|
25
|
+
return !invalid.length && readings.length === 1 && readings[0].start === 0 && readings[0].end === raw.length;
|
|
26
|
+
}
|
|
27
|
+
/** Accept only a complete monetary answer or a simple explicit payment instruction.
|
|
28
|
+
* A false result makes no claim about intent, refusal, tense or the caller's next request. */
|
|
11
29
|
export function moneyIntentAllows(input, intent) {
|
|
12
30
|
if (intent === undefined || intent === null || intent === '')
|
|
13
31
|
return true;
|
|
14
32
|
if (intent !== 'payment')
|
|
15
33
|
throw new Error('Unsupported money intent');
|
|
16
|
-
|
|
17
|
-
const refused = /\b(?:can't|cannot|can not|won't|will not|don't|do not|refuse to)\s+(?:want\s+to\s+)?pay(?:\b|(?=\d))|\bno\s+(?:lo\s+)?(?:se\s+)?(?:puede|pudo|puedo|quiero|voy\s+a)\s+pagar(?:\b|(?=\d))/.test(raw);
|
|
18
|
-
const unable = /\b(?:unable|not able)\s+to\s+pay(?:\b|(?=\d))|\bno\s+(?:soy|somos|es|son)\s+capaz(?:es)?\s+de\s+pagar(?:\b|(?=\d))|\bincapaz\s+de\s+pagar(?:\b|(?=\d))|\b(?:no\s+(?:me\s+)?es\s+posible|me\s+es\s+imposible|no\s+podr[eé])\s+pagar(?:\b|(?=\d))/.test(raw);
|
|
19
|
-
const deferred = /\b(?:pay|paying|pagar|abonar)(?:\b|(?=\d))/.test(raw) && /\b(?:later|tomorrow|next week|not today|despu[eé]s|m[aá]s tarde|ma[nñ]ana|hasta)\b/.test(raw);
|
|
20
|
-
return !refused && !unable && !deferred && !isPastPaymentStatement(raw);
|
|
34
|
+
return completeMoneyAnswer(input);
|
|
21
35
|
}
|
|
22
36
|
/** A cents-only continuation needs a complete amount; it is not an independent replacement. */
|
|
23
37
|
export function isPartialMoneyAnswer(input) {
|
|
24
38
|
return /^\s*(?:and|con|y)\s*(?:un\s+)?\d{1,2}\s*(?:cents?|centavos?)\b/i.test(String(input ?? ''));
|
|
25
39
|
}
|
|
26
|
-
/**
|
|
40
|
+
/** Compatibility predicate for a whole short historical report, never a search through prose.
|
|
41
|
+
* Payment collectors do not use this to route or answer the caller; DISPATCH owns that decision. */
|
|
27
42
|
export function isPastPaymentStatement(input) {
|
|
28
|
-
const raw = String(input ?? '').
|
|
29
|
-
return
|
|
43
|
+
const raw = String(input ?? '').trim().toLowerCase().replace(/[’‘]/g, "'").replace(/[.!]+$/, '').trim();
|
|
44
|
+
return /^(?:(?:i|we)(?:'ve| have)? (?:already |just )?paid|(?:ya )?pagu[eé])(?: \$?\d+(?:[.,]\d{1,2})?(?: (?:dollars?|d[oó]lares?))?)?$/.test(raw);
|
|
30
45
|
}
|
|
31
46
|
function unsupportedCurrency(raw) {
|
|
32
47
|
return /(?:^|[^a-záéíóúüñ])(?:pesos?|mxn|euros?|eur|pounds?|gbp|yen|jpy|cad|aud|nzd|hkd|sgd|chf|canadian|canadienses?|australian|australianos?)(?![a-záéíóúüñ])|[€£¥₱₹₩₽]|\bmx\s*\$/i.test(raw);
|
|
@@ -40,7 +55,7 @@ function introducedAsIdentifier(raw, start) {
|
|
|
40
55
|
}
|
|
41
56
|
/** Number or NaN. currency is required; cardinals defaults false and intent is optional.
|
|
42
57
|
* Explicit foreign currencies, negative amounts and independent unequal readings fail closed.
|
|
43
|
-
*
|
|
58
|
+
* Payment intent accepts a bounded whole answer; unrelated prose is never mined for an amount or consent.
|
|
44
59
|
*/
|
|
45
60
|
export function readMoneyAmount(input, options) {
|
|
46
61
|
validateMoneyOptions(options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capabilities.d.ts","sourceRoot":"","sources":["../../src/host/capabilities.js"],"names":[],"mappings":"
|
|
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,5 +1,4 @@
|
|
|
1
1
|
import { CONTINUATION_SAFETY_REQUIREMENT } from '../forms/continuation-safety.js';
|
|
2
|
-
import { SEMANTIC_INPUT_REQUIREMENT } from '../helpers/semantic-input.js';
|
|
3
2
|
import { CONTEXTUAL_RESPONSES_REQUIREMENT } from '../helpers/contextual-response.js';
|
|
4
3
|
import { INPUT_PROPOSALS_REQUIREMENT } from '../forms/proposal-runtime.js';
|
|
5
4
|
/** Declarative flow admission. No engine imports, I/O, or implicit host capability activation. */
|
|
@@ -47,7 +46,7 @@ export function assertFlowHostCapabilities(flows, capabilities = {}) {
|
|
|
47
46
|
const requirements = normalizeHostRequirements(flow?.variables?.contract?.value?.requires, flow?.id);
|
|
48
47
|
for (const capability of requirements) {
|
|
49
48
|
// Intrinsic runtime support, not a host option or an implicit host permission.
|
|
50
|
-
if (capability === CONTINUATION_SAFETY_REQUIREMENT || capability === INPUT_PROPOSALS_REQUIREMENT || capability === CONTEXTUAL_RESPONSES_REQUIREMENT
|
|
49
|
+
if (capability === CONTINUATION_SAFETY_REQUIREMENT || capability === INPUT_PROPOSALS_REQUIREMENT || capability === CONTEXTUAL_RESPONSES_REQUIREMENT)
|
|
51
50
|
continue;
|
|
52
51
|
if (capability.startsWith('jsfe:'))
|
|
53
52
|
throw new JSFEHostCapabilityError(flow?.id, capability, 'unsupported intrinsic runtime contract');
|
package/dist/index.d.ts
CHANGED
|
@@ -111,7 +111,7 @@ export declare const GUIDANCE_CONFIG_EXAMPLES: {
|
|
|
111
111
|
};
|
|
112
112
|
export declare function getSystemMessage(engine: Engine, messageId: string, context?: Record<string, unknown>): string;
|
|
113
113
|
export declare function getFlowPrompt(engine: Engine, flowName: string): string;
|
|
114
|
-
export type StepType = 'SAY' | 'SAY-GET' | 'SET' | 'CALL-TOOL' | 'FLOW' | 'SWITCH' | 'CASE' | 'RETURN' | 'END' | 'DISPATCH'
|
|
114
|
+
export type StepType = 'SAY' | 'SAY-GET' | 'SET' | 'CALL-TOOL' | 'FLOW' | 'SWITCH' | 'CASE' | 'RETURN' | 'END' | 'DISPATCH';
|
|
115
115
|
export interface ContextEntry {
|
|
116
116
|
role: 'user' | 'assistant' | 'system' | 'tool';
|
|
117
117
|
content: string | Record<string, unknown> | unknown;
|
|
@@ -149,15 +149,7 @@ export interface DetectFlowRequest {
|
|
|
149
149
|
parameters: FlowParameterDefinition[];
|
|
150
150
|
}[];
|
|
151
151
|
}
|
|
152
|
-
|
|
153
|
-
export interface InputAssessmentRequest {
|
|
154
|
-
task: 'assess_input';
|
|
155
|
-
input: string;
|
|
156
|
-
question: string;
|
|
157
|
-
purpose: string;
|
|
158
|
-
acceptance: string;
|
|
159
|
-
}
|
|
160
|
-
export type AiCallbackRequest = DetectFlowRequest | IntentStageRequest | InputAssessmentRequest;
|
|
152
|
+
export type AiCallbackRequest = DetectFlowRequest | IntentStageRequest;
|
|
161
153
|
/**
|
|
162
154
|
* @interface EngineSessionContext
|
|
163
155
|
* @property {string} sessionId - Unique identifier for the session
|