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,10 @@
|
|
|
1
|
+
/** Compile an authored synchronous calculation inside an existing SET/CASE expression.
|
|
2
|
+
* Arguments are developer-authored JavaScript source, never caller text or runtime values.
|
|
3
|
+
* This advanced helper does not change Worker.calculate's path-only argument validation.
|
|
4
|
+
*/
|
|
5
|
+
export function compileExpression(fn: any, ...args: any[]): string;
|
|
6
|
+
export function Worker(spec: any): any;
|
|
7
|
+
export function Provider(spec: any): any;
|
|
8
|
+
export function Form(spec: any): any;
|
|
9
|
+
export function Performer(spec: any): any;
|
|
10
|
+
//# sourceMappingURL=authoring.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authoring.d.ts","sourceRoot":"","sources":["../../src/forms/authoring.js"],"names":[],"mappings":"AAgDA;;;GAGG;AACH,mEAGC;AASD,uCAUC;AACD,yCAA4F;AAC5F,qCAA4F;AAC5F,0CASC"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** Concise author declarations compiled to the existing builders. No additional runtime protocol. */
|
|
2
|
+
import { defineForm, defineProvider, definePerformer, defineWorker } from './contracts.js';
|
|
3
|
+
import { FIELD_PRESETS } from './flows.js';
|
|
4
|
+
const own = (o, k) => Object.prototype.hasOwnProperty.call(o || {}, k);
|
|
5
|
+
const namePattern = /^[A-Za-z_$][\w$]*$/;
|
|
6
|
+
const forbidden = new Set(['__proto__', 'prototype', 'constructor']);
|
|
7
|
+
const safeName = name => namePattern.test(name) && !forbidden.has(name);
|
|
8
|
+
const fail = message => { throw new Error('Flow authoring: ' + message); };
|
|
9
|
+
const descriptor = value => value && typeof value === 'object' && !Array.isArray(value) && typeof value.type === 'string' && ['string', 'boolean', 'number', 'integer', 'object', 'array'].includes(value.type);
|
|
10
|
+
const variable = value => descriptor(value) ? structuredClone(value) : { type: Array.isArray(value) ? 'array' : value === null || typeof value === 'object' ? 'object' : typeof value, value: structuredClone(value) };
|
|
11
|
+
function parametersFor(parameters = []) {
|
|
12
|
+
const list = Array.isArray(parameters) ? parameters : Object.entries(parameters).map(([name, p]) => typeof p === 'string' ? { name, type: 'string', description: p } : { name, ...p });
|
|
13
|
+
const variables = {}, seen = new Set();
|
|
14
|
+
const declarations = list.map(p => {
|
|
15
|
+
if (!p || !safeName(p.name) || seen.has(p.name))
|
|
16
|
+
fail('parameter names must be unique safe identifiers');
|
|
17
|
+
seen.add(p.name);
|
|
18
|
+
const { default: initial, ...declaration } = p;
|
|
19
|
+
const type = p.type || 'string';
|
|
20
|
+
if (!['string', 'boolean', 'number', 'integer', 'object', 'array'].includes(type))
|
|
21
|
+
fail('unsupported parameter type ' + type);
|
|
22
|
+
const defaultValue = own(p, 'default') ? initial : type === 'object' ? null : type === 'array' ? [] : type === 'boolean' ? false : type === 'number' || type === 'integer' ? 0 : '';
|
|
23
|
+
variables[p.name] = { type: type === 'integer' ? 'number' : type, value: structuredClone(defaultValue) };
|
|
24
|
+
return declaration;
|
|
25
|
+
});
|
|
26
|
+
return { parameters: declarations, variables };
|
|
27
|
+
}
|
|
28
|
+
function normalize(spec, { form = false } = {}) {
|
|
29
|
+
if (!spec || typeof spec.id !== 'string' || !spec.id.trim() || spec.id !== spec.id.trim() || forbidden.has(spec.id))
|
|
30
|
+
fail('a stable flow id is required');
|
|
31
|
+
const normalized = parametersFor(spec.parameters);
|
|
32
|
+
// A field's existing description is also its public extraction declaration. Aliases stay explicit parameters.
|
|
33
|
+
if (form && spec.primary)
|
|
34
|
+
for (const field of (spec.inputs || []).flatMap(input => input.any_of || [input])) {
|
|
35
|
+
if (!field.description || normalized.parameters.some(p => p.name === field.name))
|
|
36
|
+
continue;
|
|
37
|
+
const profile = field.profile || FIELD_PRESETS[field.field]?.profile;
|
|
38
|
+
if (!profile)
|
|
39
|
+
continue;
|
|
40
|
+
const parameter = { name: field.name, type: 'string', description: field.description, ...(profile.kind === 'choice' && !profile.accept_other ? { enum: [...new Set((profile.choices || []).map(choice => choice.key))] } : {}) };
|
|
41
|
+
const extra = parametersFor([parameter]);
|
|
42
|
+
normalized.parameters.push(parameter);
|
|
43
|
+
Object.assign(normalized.variables, extra.variables);
|
|
44
|
+
}
|
|
45
|
+
const rawVariables = form ? spec.extraVars : spec.variables;
|
|
46
|
+
const variables = { ...normalized.variables, ...Object.fromEntries(Object.entries(rawVariables || {}).map(([name, v]) => [name, variable(v)])) };
|
|
47
|
+
const contract = { summary: spec.description || spec.name || spec.id, ...spec.contract };
|
|
48
|
+
return { ...spec, name: spec.name || spec.id.split(/[-:]/).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(''), parameters: normalized.parameters, contract, ...(form ? { extraVars: Object.fromEntries(Object.entries(variables).map(([name, v]) => [name, v.value])) } : { variables }) };
|
|
49
|
+
}
|
|
50
|
+
/** Serialize only declared synchronous functions; dependencies must be explicit rather than captured closures. */
|
|
51
|
+
function functionSource(fn) {
|
|
52
|
+
if (typeof fn !== 'function' || fn.constructor.name !== 'Function')
|
|
53
|
+
fail('calculations and projections require synchronous functions');
|
|
54
|
+
const source = Function.prototype.toString.call(fn);
|
|
55
|
+
if (source.includes('[native code]'))
|
|
56
|
+
fail('native functions cannot be compiled');
|
|
57
|
+
return source;
|
|
58
|
+
}
|
|
59
|
+
/** Compile an authored synchronous calculation inside an existing SET/CASE expression.
|
|
60
|
+
* Arguments are developer-authored JavaScript source, never caller text or runtime values.
|
|
61
|
+
* This advanced helper does not change Worker.calculate's path-only argument validation.
|
|
62
|
+
*/
|
|
63
|
+
export function compileExpression(fn, ...args) {
|
|
64
|
+
if (args.some(arg => typeof arg !== 'string' || !arg.trim()))
|
|
65
|
+
fail('expression arguments must be nonempty authored JavaScript expressions');
|
|
66
|
+
return `(${functionSource(fn)})(${args.join(',')})`;
|
|
67
|
+
}
|
|
68
|
+
function expression(fn, args = [], helpers = {}) {
|
|
69
|
+
if (!Array.isArray(args) || args.some(arg => typeof arg !== 'string' || !/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*$/.test(arg)))
|
|
70
|
+
fail('function arguments must be explicit variable paths');
|
|
71
|
+
const bindings = Object.entries(helpers).map(([name, helper]) => { if (!safeName(name) || ['cargo', 'form', 'formSnapshot', 'request', 'result', 'key'].includes(name))
|
|
72
|
+
fail('invalid helper binding ' + name); return `const ${name}=(${functionSource(helper)});`; }).join('\n');
|
|
73
|
+
return `(function(){${bindings}return (${functionSource(fn)})(${args.join(',')});})()`;
|
|
74
|
+
}
|
|
75
|
+
const authored = (flow, component) => ({ ...flow, metadata: { ...flow.metadata, authoring: { component } } });
|
|
76
|
+
export function Worker(spec) {
|
|
77
|
+
const { call, calculate, before = [], ...rest } = normalize(spec);
|
|
78
|
+
if ([call !== undefined, calculate !== undefined, spec.steps !== undefined].filter(Boolean).length > 1)
|
|
79
|
+
fail('Worker declares one of steps, call or calculate');
|
|
80
|
+
if (call) {
|
|
81
|
+
if (typeof call.flow !== 'string' || !call.flow)
|
|
82
|
+
fail('Worker.call needs a flow');
|
|
83
|
+
rest.steps = [...before, { id: spec.id + '_call', type: 'FLOW', value: call.flow, callType: 'call', ...(call.parameters ? { parameters: call.parameters } : {}) }];
|
|
84
|
+
}
|
|
85
|
+
else if (calculate) {
|
|
86
|
+
if (typeof calculate.result !== 'string' || !/^cargo(?:\.[A-Za-z_$][\w$]*)+$/.test(calculate.result) || calculate.result.split('.').some(part => forbidden.has(part)))
|
|
87
|
+
fail('Worker.calculate.result must be a safe cargo path');
|
|
88
|
+
rest.steps = [...before, { id: spec.id + '_calculate', type: 'SET', variable: 'noop', value: `(${calculate.result}=${expression(calculate.value, calculate.args, calculate.helpers)},true)`, requireTrue: true }];
|
|
89
|
+
rest.contract = { result: { path: calculate.result, type: 'object' }, ...rest.contract };
|
|
90
|
+
}
|
|
91
|
+
else if (before.length)
|
|
92
|
+
rest.steps = [...before, ...(rest.steps || [])];
|
|
93
|
+
return authored(defineWorker({ ...rest, contract: { role: 'worker', ...rest.contract } }), 'Worker');
|
|
94
|
+
}
|
|
95
|
+
export function Provider(spec) { return authored(defineProvider(normalize(spec)), 'Provider'); }
|
|
96
|
+
export function Form(spec) { return authored(defineForm(normalize(spec, { form: true })), 'Form'); }
|
|
97
|
+
export function Performer(spec) {
|
|
98
|
+
const normalized = normalize(spec, { form: true });
|
|
99
|
+
if (spec.provides) {
|
|
100
|
+
normalized.extraVars.provides = spec.provides;
|
|
101
|
+
}
|
|
102
|
+
if (spec.project && !Array.isArray(spec.project)) {
|
|
103
|
+
const project = spec.project;
|
|
104
|
+
const helpers = Object.entries(project.helpers || {}).map(([name, fn]) => { if (!safeName(name) || ['cargo', 'form', 'formSnapshot', 'request', 'result', 'key'].includes(name))
|
|
105
|
+
fail('invalid projection helper'); return `const ${name}=(${functionSource(fn)});`; }).join('\n');
|
|
106
|
+
normalized.project = [{ id: spec.id + '_project', type: 'SET', variable: 'noop', value: `(function(){${helpers}if((${functionSource(project.apply)})(cargo,{form:form,formSnapshot:formSnapshot,request:request,result:result,key:key})!==true)throw new Error('Performer projection must return true');return true;})()` }];
|
|
107
|
+
}
|
|
108
|
+
return authored(definePerformer(normalized), 'Performer');
|
|
109
|
+
}
|
|
@@ -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 && Number.isFinite(amountInAnswer(ac_answer)) && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
|
|
449
|
+
"value": "!ac_prechecked && ac_amount && Number.isFinite(amountInAnswer(ac_answer)) && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
|
|
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 && Number.isFinite(amountInAnswer(ac_answer)) && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
|
|
620
|
+
"value": "!ac_prechecked && ac_amount && Number.isFinite(amountInAnswer(ac_answer)) && (isAmountAnswer(ac_answer) || (ac_marked ? (ac_key === '' && /\\d\\s*(?:con|and)\\s*(?:un\\s+)?\\d{2}\\b(?!\\s*\\d)/i.test(String(ac_answer || ''))) : (ac_key === '' && (!/^\\D*\\d\\D*$/.test(String(ac_answer || '')) || /\\b(?:pay|paying|pagar|pagarle|abonar)\\b/i.test(String(ac_answer || ''))) && !/^[\\s,.;]*\\d(?:[\\s,.;]+\\d)+[\\s,.;]*$/.test(String(ac_answer || '')) && !isNaN(amountInAnswer(ac_answer))))) ? '__amount' : ac_key"
|
|
621
621
|
},
|
|
622
622
|
{
|
|
623
623
|
"id": "ac_other_request_check",
|
|
@@ -16,25 +16,29 @@ export function defineWorker({ contract, ...flow }: {
|
|
|
16
16
|
[x: string]: any;
|
|
17
17
|
contract: any;
|
|
18
18
|
}): any;
|
|
19
|
-
export function defineProvider({ provides, contract, parameters, variables, steps, ...flow }: {
|
|
19
|
+
export function defineProvider({ provides, contract, parameters, variables, steps, before, gateParameters, ...flow }: {
|
|
20
20
|
[x: string]: any;
|
|
21
21
|
provides: any;
|
|
22
22
|
contract: any;
|
|
23
23
|
parameters?: never[] | undefined;
|
|
24
24
|
variables?: {} | undefined;
|
|
25
25
|
steps: any;
|
|
26
|
+
before?: never[] | undefined;
|
|
27
|
+
gateParameters: any;
|
|
26
28
|
}): any;
|
|
27
|
-
export function defineForm({ contract, ...spec }: {
|
|
29
|
+
export function defineForm({ contract, provides, ...spec }: {
|
|
28
30
|
[x: string]: any;
|
|
29
31
|
contract: any;
|
|
32
|
+
provides: any;
|
|
30
33
|
}): any;
|
|
31
|
-
export function definePerformer({ performs, contract, prepare, present, project, ...spec }: {
|
|
34
|
+
export function definePerformer({ performs, contract, prepare, present, project, provides, ...spec }: {
|
|
32
35
|
[x: string]: any;
|
|
33
36
|
performs: any;
|
|
34
37
|
contract: any;
|
|
35
38
|
prepare: any;
|
|
36
39
|
present: any;
|
|
37
40
|
project?: never[] | undefined;
|
|
41
|
+
provides: any;
|
|
38
42
|
}): any;
|
|
39
43
|
/** A registered tool gets one generated adapter with explicit args; no dynamic tool-name interpreter is needed. */
|
|
40
44
|
export function operationWorkers(tools: any): any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/forms/contracts.js"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/forms/contracts.js"],"names":[],"mappings":"AAeA;;;IAGC;AACD;;;;;EAGC;AACD,qGAAqG;AACrG;;QAqCC;AAqBD;;;QAEC;AAgBD;;;;;;;;;QASC;AACD;;;;QAGC;AACD;;;;;;;;QA8BC;AAED,mHAAmH;AACnH,kDAgBC;AAED,+GAA+G;AAC/G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyEC"}
|
package/dist/forms/contracts.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { CONTEXTUAL_RESPONSES_REQUIREMENT, validateContextualResponseStep, contextualResponseRuntimeSteps } from '../helpers/contextual-response.js';
|
|
1
|
+
import { CONTEXTUAL_RESPONSES_REQUIREMENT, hasFormResponse, validateContextualResponseStep, contextualResponseRuntimeSteps } from '../helpers/contextual-response.js';
|
|
3
2
|
/** Build-time contracts for conversational flows. Transport operations remain registered tools. */
|
|
4
3
|
import { INPUT_PROPOSALS_REQUIREMENT, hasInputProposals, proposalRuntimeSteps } from './proposal-runtime.js';
|
|
5
4
|
import { ACTION_TOOLS } from './action-tools.js';
|
|
@@ -50,8 +49,8 @@ export function linkFormSchemas(flows, { externalFlows = [] } = {}) {
|
|
|
50
49
|
if (input.schema)
|
|
51
50
|
return objectSchema(input.schema.inputs);
|
|
52
51
|
if (input.profile?.kind === 'choice' && !input.profile.accept_other)
|
|
53
|
-
return { type: 'string', enum: (input.profile.choices || []).map(c => c.key), description: input.description || input.label || input.name };
|
|
54
|
-
return { type: 'string', description: input.description || input.label || input.name };
|
|
52
|
+
return { type: 'string', enum: (input.profile.choices || []).map(c => c.key), description: input.response?.description || input.description || input.label || input.name };
|
|
53
|
+
return { type: 'string', description: input.response?.description || input.description || input.label || input.name };
|
|
55
54
|
};
|
|
56
55
|
const objectSchema = inputs => {
|
|
57
56
|
const fields = inputs.flatMap(input => input.any_of || [input]).filter(input => input.schema || input.profile);
|
|
@@ -66,8 +65,8 @@ export function linkFormSchemas(flows, { externalFlows = [] } = {}) {
|
|
|
66
65
|
for (const input of inputs.flatMap(input => input.any_of || [input])) {
|
|
67
66
|
if (parameters.some(p => p.name === input.name) || !input.profile && !input.schema)
|
|
68
67
|
continue;
|
|
69
|
-
parameters.push(input.schema ? { name: input.name, type: 'object', jsonSchema: objectSchema(input.schema.inputs), description: input.description || input.label || input.name }
|
|
70
|
-
: { name: input.name, type: 'string', ...(input.profile.kind === 'choice' && !input.profile.accept_other ? { enum: input.profile.choices.map(c => c.key) } : {}), description: input.description || input.label || input.name });
|
|
68
|
+
parameters.push(input.schema ? { name: input.name, type: 'object', jsonSchema: objectSchema(input.schema.inputs), description: input.response?.description || input.description || input.label || input.name }
|
|
69
|
+
: { name: input.name, type: 'string', ...(input.profile.kind === 'choice' && !input.profile.accept_other ? { enum: input.profile.choices.map(c => c.key) } : {}), description: input.response?.description || input.description || input.label || input.name });
|
|
71
70
|
}
|
|
72
71
|
const linked = { ...flow, parameters, variables: { ...flow.variables, inputs: { ...flow.variables.inputs, value: inputs } } };
|
|
73
72
|
// Descendant schemas are linked after declaration; propagate their runtime requirement to the root entry.
|
|
@@ -85,8 +84,7 @@ function declared(flow, contract) {
|
|
|
85
84
|
...(step.branches ? { branches: Object.fromEntries(Object.entries(step.branches).map(([key, branch]) => [key, replacementDefaults(branch)])) } : {}),
|
|
86
85
|
...(step.onFail ? { onFail: replacementDefaults(step.onFail) } : {}) });
|
|
87
86
|
const contextual = stepList(flow.steps).filter(step => step.type === 'DISPATCH').map(step => validateContextualResponseStep(step, flow)).some(Boolean);
|
|
88
|
-
const
|
|
89
|
-
const requirements = [...normalizeHostRequirements(contract.requires, flow.id), ...(semantic ? [SEMANTIC_INPUT_REQUIREMENT] : []), ...(hasInputProposals(flow.variables?.inputs?.value) ? [INPUT_PROPOSALS_REQUIREMENT] : []), ...(contextual ? [CONTEXTUAL_RESPONSES_REQUIREMENT] : [])];
|
|
87
|
+
const requirements = [...normalizeHostRequirements(contract.requires, flow.id), ...(hasInputProposals(flow.variables?.inputs?.value) ? [INPUT_PROPOSALS_REQUIREMENT] : []), ...(contextual || hasFormResponse(flow.variables?.inputs?.value) ? [CONTEXTUAL_RESPONSES_REQUIREMENT] : [])];
|
|
90
88
|
const metadata = { version: 1, ...contract, parametersFrom: 'parameters' };
|
|
91
89
|
if (requirements.length || contract.requires !== undefined)
|
|
92
90
|
Object.defineProperty(metadata, 'requires', {
|
|
@@ -94,26 +92,50 @@ function declared(flow, contract) {
|
|
|
94
92
|
});
|
|
95
93
|
const guardedSteps = flow.steps.map(replacementDefaults);
|
|
96
94
|
// Linking a form may declare it again. Rebuild an existing protocol-only prefix once.
|
|
97
|
-
const rebuiltGuards = [...(requirements.includes(
|
|
98
|
-
if (requirements.includes(CONTEXTUAL_RESPONSES_REQUIREMENT)
|
|
95
|
+
const rebuiltGuards = [...(requirements.includes(CONTEXTUAL_RESPONSES_REQUIREMENT) ? ['contextualResponseProtocol() === 1'] : []), ...(requirements.includes(INPUT_PROPOSALS_REQUIREMENT) ? ['formProposalProtocol() === 1'] : [])];
|
|
96
|
+
if (requirements.includes(CONTEXTUAL_RESPONSES_REQUIREMENT))
|
|
99
97
|
while (guardedSteps[0]?.type === 'SET' && guardedSteps[0]?.requireTrue === true && rebuiltGuards.includes(guardedSteps[0]?.value))
|
|
100
98
|
guardedSteps.shift();
|
|
101
|
-
return { ...flow, steps:
|
|
99
|
+
return { ...flow, steps: contextualResponseRuntimeSteps(flow.id, proposalRuntimeSteps(flow.id, guardedSteps, requirements), requirements), variables: { ...flow.variables, contract: value(metadata) } };
|
|
102
100
|
}
|
|
103
101
|
export function defineWorker({ contract, ...flow }) {
|
|
104
102
|
return declared({ scope: 'isolated', version: '1.0.0', ...flow }, contract);
|
|
105
103
|
}
|
|
106
|
-
|
|
104
|
+
// Lower declarative gate arguments to a SET expression; FLOW arguments remain paths only.
|
|
105
|
+
function gateArgumentExpression(value) {
|
|
106
|
+
if (typeof value === 'string') {
|
|
107
|
+
const expression = /^\{\{([\s\S]+)\}\}$/.exec(value);
|
|
108
|
+
if (expression)
|
|
109
|
+
return '(' + expression[1] + ')';
|
|
110
|
+
if (value.includes('{{'))
|
|
111
|
+
throw new Error('Provider gate argument templates must be whole expressions');
|
|
112
|
+
return JSON.stringify(value);
|
|
113
|
+
}
|
|
114
|
+
if (Array.isArray(value))
|
|
115
|
+
return '[' + value.map(gateArgumentExpression).join(',') + ']';
|
|
116
|
+
if (value && typeof value === 'object')
|
|
117
|
+
return '{' + Object.entries(value).map(([key, entry]) => {
|
|
118
|
+
if (['__proto__', 'prototype', 'constructor'].includes(key))
|
|
119
|
+
throw new Error('Provider gate argument uses an unsafe key');
|
|
120
|
+
return JSON.stringify(key) + ':' + gateArgumentExpression(entry);
|
|
121
|
+
}).join(',') + '}';
|
|
122
|
+
return JSON.stringify(value);
|
|
123
|
+
}
|
|
124
|
+
export function defineProvider({ provides, contract, parameters = [], variables = {}, steps, before = [], gateParameters, ...flow }) {
|
|
107
125
|
const asked = providerParameter(provides);
|
|
126
|
+
if (provides.default !== undefined && ![...(provides.facts || []), ...(provides.sets || [])].some(entry => entry.key === provides.default))
|
|
127
|
+
fail(flow.id, 'provider default must name a declared fact or set');
|
|
108
128
|
return declared({ scope: 'isolated', version: '1.0.0', primary: true, ...flow,
|
|
109
|
-
parameters: [...parameters, asked], variables: { ...variables, asked: value(''), provides: value(provides) },
|
|
110
|
-
steps: steps || [{ id: `${flow.id}
|
|
129
|
+
parameters: [...parameters, asked], variables: { ...variables, ...(gateParameters !== undefined ? { provider_gate_arguments: value(null) } : {}), asked: value(''), provides: value(provides) },
|
|
130
|
+
steps: steps || [...before, ...(provides.default !== undefined ? [{ id: `${flow.id}_default`, type: 'SET', variable: 'asked', value: `asked || ${JSON.stringify(provides.default)}` }] : []),
|
|
131
|
+
...(gateParameters !== undefined ? [{ id: `${flow.id}_gate_arguments`, type: 'SET', variable: 'provider_gate_arguments', value: gateArgumentExpression(gateParameters) }] : []),
|
|
132
|
+
{ id: `${flow.id}_provide`, type: 'FLOW', value: 'provide-data', callType: 'call', parameters: { provides: '{{provides}}', asked: '{{asked}}', ...(gateParameters !== undefined ? { gate_params: '{{provider_gate_arguments}}' } : {}) } }] }, { role: 'provider', ...contract, catalog: 'provides' });
|
|
111
133
|
}
|
|
112
|
-
export function defineForm({ contract, ...spec }) {
|
|
113
|
-
const flow = formFlow(spec);
|
|
134
|
+
export function defineForm({ contract, provides, ...spec }) {
|
|
135
|
+
const flow = formFlow({ ...spec, ...(provides ? { extraVars: { ...spec.extraVars, provides, questions: providerQuestions(provides) } } : {}) });
|
|
114
136
|
return declared(flow, { role: 'collector', ...contract, form: { inputs: 'inputs' } });
|
|
115
137
|
}
|
|
116
|
-
export function definePerformer({ performs, contract, prepare, present, project = [], ...spec }) {
|
|
138
|
+
export function definePerformer({ performs, contract, prepare, present, project = [], provides, ...spec }) {
|
|
117
139
|
validateActionProjection(project, spec.id);
|
|
118
140
|
if (!Array.isArray(performs) || !performs.length || !prepare || !present)
|
|
119
141
|
fail(spec.id, 'performer needs actions, request preparation and outcome presentation');
|
|
@@ -132,7 +154,7 @@ export function definePerformer({ performs, contract, prepare, present, project
|
|
|
132
154
|
set('proposal', 'pf_record', "pf_action ? prepareFormAction(cargo, form_instance, pf_action, pf_request) : null"),
|
|
133
155
|
];
|
|
134
156
|
const flow = formFlow({ ...spec, confirm, confirmation_condition: "pf_action !== null && pf_action && typeof pf_action === 'object'",
|
|
135
|
-
extraVars: { ...spec.extraVars, performs, projection: project, pf_action: null, pf_request: null, pf_record: null, pf_result: null, pf_receipt: null },
|
|
157
|
+
extraVars: { ...spec.extraVars, ...(provides ? { provides, questions: providerQuestions(provides) } : {}), performs, projection: project, pf_action: null, pf_request: null, pf_record: null, pf_result: null, pf_receipt: null },
|
|
136
158
|
before_confirm: confirm ? [...prepareSteps, ...(spec.before_confirm || [])] : spec.before_confirm || [],
|
|
137
159
|
after: [...(confirm ? [] : prepareSteps),
|
|
138
160
|
when('perform', 'pf_action && typeof pf_action === \'object\'', call('execute', 'perform-action', { form: '{{form_instance}}', action: '{{pf_action}}', request: '{{pf_request}}', defer_receipt: true })),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/forms/flows.js"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"flows.d.ts","sourceRoot":"","sources":["../../src/forms/flows.js"],"names":[],"mappings":"AA4FA;;;;;;GAMG;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA0DC;AACD;;;GAGG;AACH;;;;;;EAGC;AA8XD,wHAAwH;AACxH,wEAaC;AACD,4FAA4F;AAC5F;;;EAYC;AACD,sGAAsG;AACtG;;;EAOC;AA9hBM,6CAAuG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqtB9G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAOG"}
|
package/dist/forms/flows.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ANSWER_WORDS } from '../helpers/answer.js';
|
|
2
|
+
import { CONTEXTUAL_RESPONSES_REQUIREMENT, hasFormResponse, contextualResponseRuntimeSteps } from '../helpers/contextual-response.js';
|
|
2
3
|
/**
|
|
3
4
|
* The FORM convention's system workers (owner direction and decisions 2026-10-19; spec: the jsfe-flow-designer skill,
|
|
4
5
|
* references/collect-input-pattern.md and references/manifests.md). This file is their SOURCE: the flows below are
|
|
@@ -116,7 +117,8 @@ export function formFlow({ id, name, version, description, inputs, after = [], e
|
|
|
116
117
|
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 } : {}),
|
|
117
118
|
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 }),
|
|
118
119
|
steps: [
|
|
119
|
-
...
|
|
120
|
+
...contextualResponseRuntimeSteps(id, [], hasFormResponse(inputs) ? [CONTEXTUAL_RESPONSES_REQUIREMENT] : []),
|
|
121
|
+
...(hasFormResponse(inputs) ? [{ ...SET(`${id}_response_reader_required`, 'noop', "typeof validateFormResponse === 'function'"), requireTrue: true }] : []),
|
|
120
122
|
...proposalRuntimeSteps(id, [], hasInputProposals(inputs) ? [INPUT_PROPOSALS_REQUIREMENT] : []),
|
|
121
123
|
SET(`${id}_resume_kind`, 'form_internal_resume', '!!form_instance'),
|
|
122
124
|
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 })`),
|
|
@@ -253,7 +255,7 @@ const collectInput = {
|
|
|
253
255
|
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 : [])"),
|
|
254
256
|
// The labels and validators ride on each reading, so the presets stay in this one flow.
|
|
255
257
|
SET('ci_enrich', 'ci_m', 'enrichFormMatches(ci_m, ci_chain, form, ci_names, current)'),
|
|
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) : ''"),
|
|
258
|
+
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.map(function(question){return Object.assign({},question,{exact:true});}), false) : ''"),
|
|
257
259
|
WHEN('ci_understood', 'ci_m.hits.length || ci_m.ambiguous.length || ci_m.questions.length || ci_qkey && ci_qkey.indexOf("__") !== 0', SIDE('ci_clear_misses', 'clearFormMisses(cargo,form,current)')),
|
|
258
260
|
SET('ci_count_words', 'ci_words', "String(cargo.choiceText || '').split(/\\s+/).filter(function (w) { return /[a-záéíóúüñ]/i.test(w); }).length"),
|
|
259
261
|
// Independent field clauses are committed before a provider can suspend on its gate.
|
|
@@ -267,7 +269,7 @@ const collectInput = {
|
|
|
267
269
|
'condition: ci_m.hits.length > 0': FLOW('ci_accept', 'collect-input-accept', 'call', { hits: '{{ci_m.hits}}' }),
|
|
268
270
|
"condition: ci_m.questions.length > 0": END('ci_question_handled'),
|
|
269
271
|
"condition: ci_qkey && ci_qkey.indexOf('__') !== 0": FLOW('ci_question_asked', 'provide-data', 'call', { form: '{{form}}', provides: '{{provides}}', asked: '{{ci_qkey}}', no_menu: 'true', no_gate: '{{ci_skip_gate}}' }),
|
|
270
|
-
|
|
272
|
+
"condition: ci_words >= 3 || ci_spec.profile.kind === 'amount' && ci_words > 0": yieldDispatch('ci_elsewhere', 'form', "'input_not_matched'"),
|
|
271
273
|
default: SIDE('ci_miss', "(missFormInput(cargo,form,current),true)")
|
|
272
274
|
} },
|
|
273
275
|
],
|
|
@@ -285,7 +287,7 @@ const validateBatch = {
|
|
|
285
287
|
id: 'validate-input-batch', name: 'ValidateInputBatch', version: '2.0.0', scope: 'isolated',
|
|
286
288
|
description: 'Worker: validate dependency-ordered candidates; return accepted, rejected and pending readings before a single commit.',
|
|
287
289
|
parameters: ['hits', 'accepted', 'rejected', 'pending', 'ignored'].map(name => ({ name, type: 'array' })),
|
|
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,
|
|
290
|
+
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_response: null, vb_proposal_values: {}, vb_proposal: null, vb_proposal_ok: true }),
|
|
289
291
|
steps: [
|
|
290
292
|
SET('vb_init_accepted', 'accepted', 'Array.isArray(accepted) ? accepted : []'),
|
|
291
293
|
SET('vb_init_rejected', 'rejected', 'Array.isArray(rejected) ? rejected : []'),
|
|
@@ -302,15 +304,9 @@ const validateBatch = {
|
|
|
302
304
|
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))"),
|
|
303
305
|
SET('vb_outcome', 'vb_outcome', "vb_known ? 'known' : (hasFormValue(vb_values[vb_h.name]) && !formValuesEqual(vb_values[vb_h.name],vb_h.value) ? 'changed' : (vb_h.current ? 'stored' : 'taken'))"),
|
|
304
306
|
SIDE('vb_reset', "(cargo.inputCheck = vb_h.invalid ? { ok: false } : (vb_h.validator && !vb_known ? null : { ok: true, value: vb_h.value }), true)"),
|
|
305
|
-
SET('
|
|
306
|
-
|
|
307
|
-
WHEN('
|
|
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}}' })),
|
|
307
|
+
SET('vb_response', 'vb_response', "(function(){var state=cargo.forms[vb_h.form],spec=state && state.specs.flatMap(function(s){return s.any_of || [s];}).find(function(s){return s.name===vb_h.name;});return spec && spec.response || null;})()"),
|
|
308
|
+
WHEN('vb_contextual_needed', "vb_ready === true && vb_response && !vb_known && !vb_h.invalid && vb_h.origin !== 'activation' && !vb_h.fromPending", FLOW('vb_read_response', 'read-form-response', 'call', { form: '{{vb_h.form}}', input: '{{vb_h.name}}' })),
|
|
309
|
+
WHEN('vb_validator', 'vb_ready === true && vb_h.validator && !vb_known && !vb_h.invalid', FLOW('vb_validate', '{{vb_h.validator}}', 'call', { form: '{{vb_h.form}}', input: '{{vb_h.name}}', value: '{{vb_h.value}}', values: '{{vb_values}}', reading: '{{vb_h}}' })),
|
|
314
310
|
WHEN('vb_refused', 'vb_h.refused === true || vb_h.incompleteMoney === true', SIDE('vb_withhold_refusal', "(cargo.inputCheck=Object.assign({},cargo.inputCheck || {},{ok:false}),true)")),
|
|
315
311
|
SET('vb_candidate', 'vb_candidate', "Object.assign({},vb_h,{ok:!!(cargo.inputCheck && cargo.inputCheck.ok === true),value:cargo.inputCheck && cargo.inputCheck.value !== undefined && cargo.inputCheck.value !== null ? cargo.inputCheck.value : vb_h.value,message:cargo.inputCheck && cargo.inputCheck.message,message_es:cargo.inputCheck && cargo.inputCheck.message_es})"),
|
|
316
312
|
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'),
|
|
@@ -329,25 +325,26 @@ const requestCancelled = {
|
|
|
329
325
|
steps: [SET('cancel_request_owner', 'cancelled', 'cancelFormTask(cargo,form)'),
|
|
330
326
|
{ 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
327
|
};
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
SET('
|
|
339
|
-
SET('
|
|
340
|
-
|
|
341
|
-
|
|
328
|
+
// Open-ended answers use the same contextual intent/extraction path as other DISPATCH replies.
|
|
329
|
+
const readFormResponse = {
|
|
330
|
+
id: 'read-form-response', name: 'ReadFormResponse', version: '1.0.0', scope: 'isolated', description: 'Read the requested field with contextual DISPATCH; uncertainty returns to the host with saved form progress.',
|
|
331
|
+
parameters: [{ name: 'form', type: 'string' }, { name: 'input', type: 'string' }],
|
|
332
|
+
variables: vars({ group: null, spec: null, question: '', reply: null }),
|
|
333
|
+
steps: [SET('response_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;});})"),
|
|
334
|
+
SET('response_spec', 'spec', "group && (group.any_of ? group.any_of.find(function(s){return s.name===input;}) : group)"),
|
|
335
|
+
{ ...SET('response_declared', 'noop', '!!spec && !!validateFormResponse(spec.response)'), requireTrue: true },
|
|
336
|
+
SET('response_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)"),
|
|
337
|
+
SET('response_clear', 'reply', 'null'),
|
|
338
|
+
{ ...yieldDispatch('response_dispatch', 'form', "'input_not_matched'"), onResponse: 'continue', responseContext: 'Current question: {{question}}. Requested answer: {{spec.response.description}}. Continue only for an answer to this question. A changed request belongs to its workflow; an unrelated question or uncertain response belongs to the host.', responseParameters: [{ name: 'answer', type: 'string', description: '{{spec.response.description}}' }], responseVariable: 'reply' },
|
|
339
|
+
WHEN('response_missing', "!reply || typeof reply.answer !== 'string' || !reply.answer.trim()", yieldDispatch('response_handoff', 'form', "'input_not_matched'"))]
|
|
342
340
|
};
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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)")] });
|
|
341
|
+
const collectContextualAnswer = formFlow({ id: 'collect-contextual-answer', name: 'CollectContextualAnswer', description: 'Collect one open-ended answer using contextual DISPATCH and preserve the caller wording.',
|
|
342
|
+
parameters: [...['question', 'question_es', 'description', 'context', 'context_es'].map(name => ({ name, type: 'string' })), { name: 'choices', type: 'array' }, { name: 'digits', type: 'object' }],
|
|
343
|
+
extraVars: { question: '', question_es: '', description: '', context: 'your request', context_es: 'su solicitud', choices: [], digits: null },
|
|
344
|
+
inputs: [{ name: 'answer', profile: { kind: 'text', narrative: true }, response: { description: 'The answer to the current question, in the caller’s words.' }, question_from: 'question' }],
|
|
345
|
+
before: [{ ...SET('response_policy_required', 'noop', "typeof description==='string' && !!description.trim()"), requireTrue: true },
|
|
346
|
+
SIDE('response_declaration', "(function(){var state=cargo.forms[form_instance];state.data={question:question,question_es:question_es};state.specs[0].response={description:description};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('response_context', 'exit_context', 'context'), SET('response_context_es', 'exit_context_es', 'context_es')],
|
|
347
|
+
after: [SIDE('response_return', "(cargo.choice=cargo.forms[form_instance].values.answer,true)")] });
|
|
351
348
|
const accept = {
|
|
352
349
|
id: 'collect-input-accept', name: 'CollectInputAccept', version: '2.0.0', scope: 'isolated',
|
|
353
350
|
description: 'Worker: validate all readings, commit accepted changes once with transitive invalidation, then acknowledge and run declared callbacks.',
|
|
@@ -427,7 +424,7 @@ const confirmForm = {
|
|
|
427
424
|
variables: vars({ cf_presets: FIELD_PRESETS, cf_chain: [], cf_m: null, cf_current: null, cf_result: '', cf_prompt: '', cf_prompt_es: '', cf_words: 0, cf_tries: 0, words: [], clarifications: [], no_keys: ['2'], interrupts: [], cf_choices: [], cf_event: '', cf_amount: false, cf_questions: [], cf_provides: null, cf_skip_gate: '' }),
|
|
428
425
|
steps: [
|
|
429
426
|
SIDE('cf_reset', "(cargo.formConfirm = cargo.formConfirm || {}, cargo.formConfirm[form] = '', true)"),
|
|
430
|
-
SET('cf_choices', 'cf_choices',
|
|
427
|
+
SET('cf_choices', 'cf_choices', `[{key:'yes',words:['1'].concat(Array.isArray(words)?words:[]),exact:true},{key:'no',words:(Array.isArray(no_keys)?no_keys:['2']).concat(${JSON.stringify(ANSWER_WORDS.no)}),exact:true}].concat((Array.isArray(interrupts)?interrupts:[]).map(function(event){return {key:'event:'+event.key,words:event.words,exact:event.exact!==false};}))`),
|
|
431
428
|
SET('cf_initial_chain', 'cf_chain', CHAIN_JS),
|
|
432
429
|
SET('cf_amount_context', 'cf_amount', "cf_chain.some(function(input){return input.profile && input.profile.kind==='amount';})"),
|
|
433
430
|
SET('cf_prompt', 'cf_prompt', "formInputPrompt(cargo,form,'__confirm',{question:question,question_es:question_es},{},'en')"),
|
|
@@ -454,7 +451,7 @@ const confirmForm = {
|
|
|
454
451
|
'condition: cf_m.hits.length > 0': FLOW('cf_accept', 'collect-input-accept', 'call', { hits: '{{cf_m.hits}}' }),
|
|
455
452
|
"condition: cargo.choice === 'no'": SET('cf_declined', 'cf_result', "'no'"),
|
|
456
453
|
"condition: Array.isArray(clarifications) && pickChoice(String(cargo.choiceText || '').replace(/[?¿]/g,''),[{key:'clarify',words:clarifications,exact:true}],false)==='clarify'": SET('cf_clarification', 'cf_result', "'clarification'"),
|
|
457
|
-
'condition: cf_words >= 3': yieldDispatch('cf_elsewhere', 'form', "'confirmation_not_matched'"),
|
|
454
|
+
'condition: cf_words >= 3 || cf_amount && cf_words > 0': yieldDispatch('cf_elsewhere', 'form', "'confirmation_not_matched'"),
|
|
458
455
|
default: SET('cf_unclear', 'cf_result', "'unclear'")
|
|
459
456
|
} },
|
|
460
457
|
SET('cf_changed', 'cf_result', "cf_result ? cf_result : 'changed'"),
|
|
@@ -746,16 +743,16 @@ const resumeForm = { id: 'resume-form', name: 'ResumeForm', version: '1.0.0', sc
|
|
|
746
743
|
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 || ''"),
|
|
747
744
|
FLOW('resume_owned_form', '{{target}}', 'replace', { form_instance: '{{form}}', parent_form: '{{parent}}', result_input: '{{slot}}' })
|
|
748
745
|
] };
|
|
749
|
-
const LIBRARY_FLOWS = [confirmInputProposal, proposalDeclined, resumeForm, performAction, sendTextAction, prepareInput, runForm, collectInput, validateBatch, requestCancelled,
|
|
746
|
+
const LIBRARY_FLOWS = [confirmInputProposal, proposalDeclined, resumeForm, performAction, sendTextAction, prepareInput, runForm, collectInput, validateBatch, requestCancelled, readFormResponse, collectContextualAnswer, accept, acceptedEffects, disambiguate, confirmForm, formDone, providerMenu, ...validators, ...fieldCollectors, ...subForms, provideData, provideQueuedData, loadSource, answerFacts];
|
|
750
747
|
const LIBRARY_CONTRACTS = {
|
|
751
748
|
'confirm-input-proposal': { role: 'collector', requires: [INPUT_PROPOSALS_REQUIREMENT] }, 'confirm-input-proposal-declined': { role: 'worker', requires: [INPUT_PROPOSALS_REQUIREMENT] },
|
|
752
749
|
'resume-form': { role: 'worker' },
|
|
753
750
|
'perform-action': { role: 'worker', tools: ['jsfe:action-claim', 'jsfe:action-complete'], result: { path: 'cargo.actionResult', type: 'object' } },
|
|
754
751
|
'send-text-action': { role: 'worker', result: { path: 'cargo.actionOutcome', type: 'object' } },
|
|
755
752
|
'prepare-input': { role: 'worker' }, 'run-form': { role: 'worker' }, 'collect-input': { role: 'worker' },
|
|
756
|
-
'request-cancelled': { role: 'worker'
|
|
757
|
-
'
|
|
758
|
-
'collect-
|
|
753
|
+
'request-cancelled': { role: 'worker' },
|
|
754
|
+
'read-form-response': { role: 'worker', requires: [CONTEXTUAL_RESPONSES_REQUIREMENT] },
|
|
755
|
+
'collect-contextual-answer': { role: 'collector', requires: [CONTEXTUAL_RESPONSES_REQUIREMENT] },
|
|
759
756
|
'validate-input-batch': { role: 'worker', result: { path: 'cargo.inputBatch', type: 'object' } },
|
|
760
757
|
'collect-input-accept': { role: 'worker' }, 'input-accepted-effects': { role: 'worker' },
|
|
761
758
|
'disambiguate-input': { role: 'worker' }, 'confirm-form': { role: 'worker' }, 'form-done': { role: 'worker' },
|
|
@@ -776,6 +773,6 @@ export const FLOWS = LIBRARY_FLOWS.map(flow => {
|
|
|
776
773
|
throw new Error('Shared worker needs an explicit contract: ' + flow.id);
|
|
777
774
|
if ((declaration.role === 'collector') !== (flow.metadata?.formProtocol === 2))
|
|
778
775
|
throw new Error('Shared collector contract mismatch: ' + flow.id);
|
|
779
|
-
return { ...flow, steps:
|
|
776
|
+
return { ...flow, steps: contextualResponseRuntimeSteps(flow.id, proposalRuntimeSteps(flow.id, flow.steps, declaration.requires), declaration.requires), variables: { ...flow.variables, contract: { type: 'object', value: { version: 1, summary: flow.description,
|
|
780
777
|
parametersFrom: 'parameters', ...declaration, ...(declaration.role === 'collector' ? { form: { inputs: 'inputs' } } : {}) } } } };
|
|
781
778
|
});
|
package/dist/forms/index.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
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 { explainSession } from "./inspection.js";
|
|
4
5
|
export { withSafetyRevision, CONTINUATION_SAFETY_REQUIREMENT } from "./continuation-safety.js";
|
|
5
6
|
export { FIELD_PRESETS, formFlow, declinedFlow, textValue } from "./flows.js";
|
|
6
7
|
export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from "./contracts.js";
|
|
7
8
|
export { addressDraft, zipLocation, streetLocation, resolvedAddress } from "../helpers/address.js";
|
|
9
|
+
export { Form, Provider, Performer, Worker, compileExpression } from "./authoring.js";
|
|
8
10
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/forms/index.js
CHANGED
|
@@ -4,9 +4,11 @@ import { FLOWS as ADDRESS_FLOWS } from './address-flows.js';
|
|
|
4
4
|
import { FLOWS as FORM_FLOWS } from './flows.js';
|
|
5
5
|
import { FLOWS as CHOICE_FLOWS } from './choice-flow.js';
|
|
6
6
|
import { FLOWS as IDENTITY } from './identity-flows.js';
|
|
7
|
-
export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY].map(flow => withSafetyRevision(flow, '
|
|
7
|
+
export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY].map(flow => withSafetyRevision(flow, 'dispatch-intake-2026-10-22'));
|
|
8
8
|
export { FIELD_PRESETS, formFlow, declinedFlow, textValue } from './flows.js';
|
|
9
9
|
export { FLOWS as IDENTITY_FLOWS } from './identity-flows.js';
|
|
10
10
|
export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from './contracts.js';
|
|
11
11
|
export { compileFormPrompts } from './prompt-compiler.js';
|
|
12
12
|
export { addressDraft, zipLocation, streetLocation, resolvedAddress } from '../helpers/address.js';
|
|
13
|
+
export { explainSession } from './inspection.js';
|
|
14
|
+
export { Form, Provider, Performer, Worker, compileExpression } from './authoring.js';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Explain existing state; this neither authorizes an action nor records an event history.
|
|
2
|
+
* Values, request bodies, caller words and rendered questions are intentionally omitted.
|
|
3
|
+
* `previous` adds only observable field changes and invalidated confirmations; it cannot
|
|
4
|
+
* reconstruct intermediate events between the two snapshots.
|
|
5
|
+
*/
|
|
6
|
+
export function explainSession(session: any, { flows, previous }?: {
|
|
7
|
+
flows?: never[] | undefined;
|
|
8
|
+
}): {
|
|
9
|
+
status: string;
|
|
10
|
+
entries: any[];
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=inspection.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inspection.d.ts","sourceRoot":"","sources":["../../src/forms/inspection.js"],"names":[],"mappings":"AAOA;;;;GAIG;AACH;;;;;EAkFC"}
|