jsfe 1.7.8 → 1.7.10
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/README.md +2 -3
- package/dist/forms/authoring.d.ts +10 -0
- package/dist/forms/authoring.d.ts.map +1 -0
- package/dist/forms/authoring.js +110 -0
- package/dist/forms/choice-flow.d.ts +0 -4
- package/dist/forms/choice-flow.d.ts.map +1 -1
- package/dist/forms/choice-flow.js +10 -14
- package/dist/forms/continuation-safety.d.ts.map +1 -1
- package/dist/forms/continuation-safety.js +2 -1
- package/dist/forms/contracts.d.ts +8 -4
- package/dist/forms/contracts.d.ts.map +1 -1
- package/dist/forms/contracts.js +46 -23
- package/dist/forms/declaration-capture.d.ts +7 -0
- package/dist/forms/declaration-capture.d.ts.map +1 -0
- package/dist/forms/declaration-capture.js +15 -0
- package/dist/forms/declarations.d.ts +20 -0
- package/dist/forms/declarations.d.ts.map +1 -0
- package/dist/forms/declarations.js +272 -0
- package/dist/forms/flows.d.ts.map +1 -1
- package/dist/forms/flows.js +47 -50
- package/dist/forms/identity-flows.js +8 -8
- package/dist/forms/index.d.ts +4 -0
- package/dist/forms/index.js +5 -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/forms/prompt-compiler.d.ts.map +1 -1
- package/dist/forms/prompt-compiler.js +5 -1
- package/dist/helpers/answer.d.ts +1 -1
- package/dist/helpers/answer.js +2 -2
- 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-sources.js +1 -1
- 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 +6 -5
- package/dist/helpers/index.d.ts.map +1 -1
- package/dist/helpers/index.js +4 -4
- package/dist/helpers/match-inputs.d.ts.map +1 -1
- package/dist/helpers/match-inputs.js +12 -40
- 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/helpers/named-functions.d.ts +5 -0
- package/dist/helpers/named-functions.d.ts.map +1 -0
- package/dist/helpers/named-functions.js +54 -0
- package/dist/helpers/proposal-contract.js +4 -4
- package/dist/host/capabilities.d.ts.map +1 -1
- package/dist/host/capabilities.js +11 -3
- package/dist/host/registry-composition.d.ts.map +1 -1
- package/dist/host/registry-composition.js +9 -3
- package/dist/index.d.ts +15 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +80 -51
- package/dist/runtime-identity.js +1 -1
- package/docs/copilot-reference.md +336 -66
- package/docs/development-release.md +16 -1
- package/package.json +1 -2
- 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
- package/docs/forms.md +0 -271
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/** JSON declarations lower through the same authoring builders as programmatic declarations. */
|
|
2
|
+
import { Form, Provider, Performer, Worker } from './authoring.js';
|
|
3
|
+
import { linkFormSchemas, validateFlowContracts } from './contracts.js';
|
|
4
|
+
import { compileFormPrompts } from './prompt-compiler.js';
|
|
5
|
+
import { withSafetyRevision } from './continuation-safety.js';
|
|
6
|
+
import { capturedAuthorSpec, copyAuthorSpec, authoredExpressions } from './declaration-capture.js';
|
|
7
|
+
const formKeys = new Set(['inputs', 'before', 'after', 'confirm', 'before_confirm', 'declined', 'stop', 'close_on_stop', 'resume_on_parent_change', 'done', 'validator', 'confirmation_condition', 'prompt', 'prompt_es', 'incomplete_outcome', 'on_exhausted']);
|
|
8
|
+
const sharedKeys = ['id', 'name', 'description', 'version', 'scope', 'primary', 'parameters', 'contract', 'parameterInstructions'];
|
|
9
|
+
const safe = /^[A-Za-z_$][\w$]*$/;
|
|
10
|
+
const fail = message => { throw new Error('Flow declaration: ' + message); };
|
|
11
|
+
// Trusted-author change detection, not an authentication signature. Stable in browsers and Node.
|
|
12
|
+
function sourceRevision(source) { const text = JSON.stringify(source); const hashes = [2166136261, 2246822507, 3266489909, 668265263]; for (let i = 0; i < text.length; i++)
|
|
13
|
+
for (let lane = 0; lane < hashes.length; lane++)
|
|
14
|
+
hashes[lane] = Math.imul(hashes[lane] ^ text.charCodeAt(i), 16777619 + lane * 2) >>> 0; return hashes.map(n => n.toString(16).padStart(8, '0')).join(''); }
|
|
15
|
+
const variableDeclaration = value => value && typeof value === 'object' && !Array.isArray(value) && ['string', 'number', 'integer', 'boolean', 'object', 'array'].includes(value.type) ? value : { type: Array.isArray(value) ? 'array' : value === null || typeof value === 'object' ? 'object' : typeof value, value };
|
|
16
|
+
/** Compile only explicitly versioned declarations. Ordinary executable JSON is unchanged.
|
|
17
|
+
* @param {any[]} flows
|
|
18
|
+
* @param {{tools?: any[], externalFlows?: any[], validate?: boolean}} options
|
|
19
|
+
* @returns {any[]}
|
|
20
|
+
*/
|
|
21
|
+
export function compileFlowDeclarations(flows, { tools, externalFlows = [], validate = true } = {}) {
|
|
22
|
+
if (!Array.isArray(flows))
|
|
23
|
+
fail('flows must be an array');
|
|
24
|
+
if (!flows.some(flow => flow?.declarationVersion !== undefined))
|
|
25
|
+
return flows;
|
|
26
|
+
const ids = new Set();
|
|
27
|
+
for (const flow of flows) {
|
|
28
|
+
if (ids.has(flow.id))
|
|
29
|
+
fail('duplicate flow id ' + flow.id);
|
|
30
|
+
ids.add(flow.id);
|
|
31
|
+
}
|
|
32
|
+
const compiled = flows.map(source => {
|
|
33
|
+
if (source.declarationVersion === undefined)
|
|
34
|
+
return source;
|
|
35
|
+
if (source.declarationVersion !== 1)
|
|
36
|
+
fail('unsupported declarationVersion on ' + source.id);
|
|
37
|
+
const { declarationVersion, form, functions, safetyRevision, ...rest } = structuredClone(source);
|
|
38
|
+
if (Object.hasOwn(source, 'form') && (!form || typeof form !== 'object' || !Array.isArray(form.inputs)))
|
|
39
|
+
fail(source.id + ' form requires inputs');
|
|
40
|
+
if (form && [...formKeys].some(key => Object.hasOwn(rest, key)))
|
|
41
|
+
fail(source.id + ' form options must be inside form');
|
|
42
|
+
if (form && rest.steps)
|
|
43
|
+
fail(source.id + ' cannot combine form and executable steps');
|
|
44
|
+
if (rest.performs && !form)
|
|
45
|
+
fail(source.id + ' performs requires form');
|
|
46
|
+
if (functions !== undefined && (!functions || Array.isArray(functions) || typeof functions !== 'object'))
|
|
47
|
+
fail(source.id + ' functions must be a map');
|
|
48
|
+
const spec = form ? { ...rest, ...form, extraVars: Object.fromEntries(Object.entries(rest.variables || {}).map(([name, value]) => [name, value && typeof value === 'object' && Object.hasOwn(value, 'value') ? value.value : value])) } : rest;
|
|
49
|
+
if (form)
|
|
50
|
+
delete spec.variables;
|
|
51
|
+
let flow = rest.performs ? Performer(spec) : form ? Form(spec) : rest.provides ? Provider(spec) : Worker(spec);
|
|
52
|
+
const parameterNames = new Set();
|
|
53
|
+
flow = { ...flow, parameters: (flow.parameters || []).filter(parameter => { if (parameterNames.has(parameter.name))
|
|
54
|
+
return false; parameterNames.add(parameter.name); return true; }), ...(rest.parameterInstructions !== undefined ? { parameterInstructions: rest.parameterInstructions } : {}), ...(functions ? { functions } : {}), metadata: { ...flow.metadata, declaration: { version: 1, source: source.id } } };
|
|
55
|
+
// Revisions are engine bookkeeping; a stale authored token cannot override source change detection.
|
|
56
|
+
const { safetyRevision: ignoredRevision, ...revisionSource } = source;
|
|
57
|
+
return withSafetyRevision(flow, 'declaration-v1:' + sourceRevision(revisionSource));
|
|
58
|
+
});
|
|
59
|
+
const externalObjects = externalFlows.filter(flow => flow && typeof flow === 'object');
|
|
60
|
+
const formIds = new Set(flows.filter(flow => flow.declarationVersion === 1 && flow.form).map(flow => flow.id));
|
|
61
|
+
const prompted = compileFormPrompts(compiled.filter(flow => formIds.has(flow.id)));
|
|
62
|
+
const promptOwners = new Map(prompted.filter(flow => formIds.has(flow.id)).map(flow => [flow.id, flow]));
|
|
63
|
+
const generated = prompted.filter(flow => !formIds.has(flow.id));
|
|
64
|
+
const installedIds = new Set([...ids, ...externalFlows.map(flow => typeof flow === 'string' ? flow : flow.id)]);
|
|
65
|
+
for (const worker of generated) {
|
|
66
|
+
if (installedIds.has(worker.id))
|
|
67
|
+
fail('generated question worker id collision ' + worker.id);
|
|
68
|
+
installedIds.add(worker.id);
|
|
69
|
+
}
|
|
70
|
+
const linked = linkFormSchemas([...compiled.map(flow => promptOwners.get(flow.id) || flow), ...generated], { externalFlows: externalObjects });
|
|
71
|
+
if (validate) {
|
|
72
|
+
const declaredIds = new Set([...flows.filter(flow => flow.declarationVersion === 1).map(flow => flow.id), ...generated.map(flow => flow.id)]);
|
|
73
|
+
// Loading a declaration must not opt unrelated executable host/shared flows into authoring contracts.
|
|
74
|
+
const declared = linked.filter(flow => declaredIds.has(flow.id));
|
|
75
|
+
const installed = [...externalFlows.map(flow => typeof flow === 'string' ? flow : flow.id), ...linked.filter(flow => !declaredIds.has(flow.id)).map(flow => flow.id)];
|
|
76
|
+
validateFlowContracts(declared, tools || [], { externalFlows: [...new Set(installed)] });
|
|
77
|
+
}
|
|
78
|
+
return linked;
|
|
79
|
+
}
|
|
80
|
+
/** Return the original programmatic declaration, even after ordinary spread/clone transformations. */
|
|
81
|
+
export function captureOriginalDeclaration(flow) { const saved = capturedAuthorSpec(flow); return saved ? { component: saved.component, spec: copyAuthorSpec(saved.spec) } : null; }
|
|
82
|
+
function splitParameters(text) {
|
|
83
|
+
const parts = [];
|
|
84
|
+
let start = 0, depth = 0, quote = '', escape = false;
|
|
85
|
+
for (let i = 0; i < text.length; i++) {
|
|
86
|
+
const c = text[i];
|
|
87
|
+
if (quote) {
|
|
88
|
+
if (escape)
|
|
89
|
+
escape = false;
|
|
90
|
+
else if (c === '\\')
|
|
91
|
+
escape = true;
|
|
92
|
+
else if (c === quote)
|
|
93
|
+
quote = '';
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if ('"\'`'.includes(c)) {
|
|
97
|
+
quote = c;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if ('([{'.includes(c))
|
|
101
|
+
depth++;
|
|
102
|
+
if (')]}'.includes(c))
|
|
103
|
+
depth--;
|
|
104
|
+
if (c === ',' && !depth) {
|
|
105
|
+
parts.push(text.slice(start, i).trim());
|
|
106
|
+
start = i + 1;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (text.slice(start).trim())
|
|
110
|
+
parts.push(text.slice(start).trim());
|
|
111
|
+
return parts;
|
|
112
|
+
}
|
|
113
|
+
/** Ordinary synchronous JavaScript source becomes named parameters and body lines, not a new language. */
|
|
114
|
+
function functionDefinition(fn) {
|
|
115
|
+
if (typeof fn !== 'function' && !(fn && typeof fn.source === 'string'))
|
|
116
|
+
fail('only synchronous JavaScript functions can be serialized');
|
|
117
|
+
if (typeof fn === 'function' && fn.constructor.name !== 'Function')
|
|
118
|
+
fail('only synchronous JavaScript functions can be serialized');
|
|
119
|
+
const source = (typeof fn === 'function' ? Function.prototype.toString.call(fn) : fn.source).trim();
|
|
120
|
+
let parameters, body;
|
|
121
|
+
if (/^(?:function\b|[A-Za-z_$][\w$]*\s*\()/.test(source)) {
|
|
122
|
+
const start = source.indexOf('(');
|
|
123
|
+
let depth = 1, end = start + 1, quote = '';
|
|
124
|
+
for (; end < source.length; end++) {
|
|
125
|
+
const c = source[end];
|
|
126
|
+
if (quote) {
|
|
127
|
+
if (c === quote && source[end - 1] !== '\\')
|
|
128
|
+
quote = '';
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if ('"\'`'.includes(c)) {
|
|
132
|
+
quote = c;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (c === '(')
|
|
136
|
+
depth++;
|
|
137
|
+
if (c === ')' && !--depth)
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
parameters = splitParameters(source.slice(start + 1, end));
|
|
141
|
+
const open = source.indexOf('{', end);
|
|
142
|
+
body = source.slice(open + 1, source.lastIndexOf('}'));
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
const arrow = source.indexOf('=>');
|
|
146
|
+
if (arrow < 0)
|
|
147
|
+
fail('unsupported function source');
|
|
148
|
+
let head = source.slice(0, arrow).trim();
|
|
149
|
+
if (head.startsWith('('))
|
|
150
|
+
head = head.slice(1, -1);
|
|
151
|
+
parameters = splitParameters(head);
|
|
152
|
+
const tail = source.slice(arrow + 2).trim();
|
|
153
|
+
body = tail.startsWith('{') ? tail.slice(1, -1) : 'return (' + tail + ');';
|
|
154
|
+
}
|
|
155
|
+
const prelude = [];
|
|
156
|
+
const used = new Set(parameters.filter(p => safe.test(p)));
|
|
157
|
+
const args = parameters.map((raw, i) => { if (safe.test(raw))
|
|
158
|
+
return { name: raw }; let name = 'argument' + i; while (used.has(name))
|
|
159
|
+
name += '_'; used.add(name); if (raw.startsWith('...')) {
|
|
160
|
+
const target = raw.slice(3);
|
|
161
|
+
prelude.push('const ' + target + ' = ' + name + ';');
|
|
162
|
+
return { name, rest: true };
|
|
163
|
+
} let depth = 0, equals = -1; for (let j = 0; j < raw.length; j++) {
|
|
164
|
+
if ('([{'.includes(raw[j]))
|
|
165
|
+
depth++;
|
|
166
|
+
else if (')]}'.includes(raw[j]))
|
|
167
|
+
depth--;
|
|
168
|
+
else if (raw[j] === '=' && !depth) {
|
|
169
|
+
equals = j;
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
} if (equals >= 0) {
|
|
173
|
+
const binding = raw.slice(0, equals).trim();
|
|
174
|
+
prelude.push('let ' + binding + ' = ' + name + ' === undefined ? (' + raw.slice(equals + 1) + ') : ' + name + ';');
|
|
175
|
+
}
|
|
176
|
+
else
|
|
177
|
+
prelude.push('const ' + raw + ' = ' + name + ';'); return { name }; });
|
|
178
|
+
return { ...(fn.name && safe.test(fn.name) ? { name: fn.name } : {}), parameters: args, body: [...prelude, ...body.trim().split('\n')] };
|
|
179
|
+
}
|
|
180
|
+
/** One-time migration of an authored builder to the editable, self-contained JSON format. */
|
|
181
|
+
export function serializeFlowDeclaration(flow, { resolvedFlow = flow } = {}) {
|
|
182
|
+
const saved = capturedAuthorSpec(flow);
|
|
183
|
+
if (!saved)
|
|
184
|
+
return structuredClone(resolvedFlow);
|
|
185
|
+
const spec = copyAuthorSpec(saved.spec), registry = {}, sources = new Map();
|
|
186
|
+
const register = (fn, preferred) => {
|
|
187
|
+
const source = typeof fn === 'function' ? Function.prototype.toString.call(fn) : fn.source;
|
|
188
|
+
let name = preferred || fn.name || 'calculation';
|
|
189
|
+
if (!safe.test(name))
|
|
190
|
+
name = 'calculation';
|
|
191
|
+
let suffix = 2;
|
|
192
|
+
while (registry[name] && sources.get(name) !== source)
|
|
193
|
+
name = (preferred || fn.name || 'calculation') + '_' + suffix++;
|
|
194
|
+
if (!registry[name]) {
|
|
195
|
+
registry[name] = functionDefinition(fn);
|
|
196
|
+
sources.set(name, source);
|
|
197
|
+
}
|
|
198
|
+
return name;
|
|
199
|
+
};
|
|
200
|
+
const helpers = items => { for (const [name, fn] of Object.entries(items || {}))
|
|
201
|
+
register(fn, name); };
|
|
202
|
+
const rewrite = value => {
|
|
203
|
+
if (typeof value === 'string') {
|
|
204
|
+
// Outer expressions first: their arguments can themselves contain authored expressions.
|
|
205
|
+
for (const [source, entry] of [...authoredExpressions()].sort((a, b) => b[0].length - a[0].length))
|
|
206
|
+
if (value.includes(source)) {
|
|
207
|
+
const name = register(entry);
|
|
208
|
+
value = value.split(source).join('fn.' + name + '(' + entry.args.map(rewrite).join(',') + ')');
|
|
209
|
+
}
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
if (typeof value === 'function')
|
|
213
|
+
fail('a function must be a declared calculation, projection or helper');
|
|
214
|
+
if (Array.isArray(value))
|
|
215
|
+
return value.map(rewrite);
|
|
216
|
+
if (value && typeof value === 'object')
|
|
217
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, rewrite(item)]));
|
|
218
|
+
return value;
|
|
219
|
+
};
|
|
220
|
+
helpers(spec.helpers);
|
|
221
|
+
if (spec.calculate) {
|
|
222
|
+
const c = spec.calculate;
|
|
223
|
+
helpers(c.helpers);
|
|
224
|
+
const name = register(c.value);
|
|
225
|
+
spec.steps = [...(spec.before || []), { id: spec.id + '_calculate', type: 'SET', variable: 'noop', value: `(${c.result}=fn.${name}(${(c.args || []).join(',')}),true)`, requireTrue: true }];
|
|
226
|
+
spec.contract = { result: { path: c.result, type: 'object' }, ...spec.contract };
|
|
227
|
+
delete spec.calculate;
|
|
228
|
+
delete spec.before;
|
|
229
|
+
}
|
|
230
|
+
if (spec.project && !Array.isArray(spec.project)) {
|
|
231
|
+
helpers(spec.project.helpers);
|
|
232
|
+
const name = register(spec.project.apply);
|
|
233
|
+
spec.project = [{ id: spec.id + '_project', type: 'SET', variable: 'noop', value: `(function(){if(fn.${name}(cargo,{form:form,formSnapshot:formSnapshot,request:request,result:result,key:key})!==true)throw new Error('Performer projection must return true');return true;})()` }];
|
|
234
|
+
}
|
|
235
|
+
const result = { declarationVersion: 1 };
|
|
236
|
+
for (const key of sharedKeys)
|
|
237
|
+
if (spec[key] !== undefined)
|
|
238
|
+
result[key] = spec[key];
|
|
239
|
+
for (const key of ['name', 'description', 'parameters', 'primary', 'scope', 'parameterInstructions'])
|
|
240
|
+
if (resolvedFlow[key] !== undefined)
|
|
241
|
+
result[key] = structuredClone(resolvedFlow[key]);
|
|
242
|
+
const originalParameters = Array.isArray(spec.parameters) ? spec.parameters : Object.entries(spec.parameters || {}).map(([name, value]) => ({ name, ...(typeof value === 'object' ? value : {}) }));
|
|
243
|
+
const serializedParameterNames = new Set();
|
|
244
|
+
if (result.parameters)
|
|
245
|
+
result.parameters = result.parameters.filter(parameter => { if (serializedParameterNames.has(parameter.name))
|
|
246
|
+
return false; serializedParameterNames.add(parameter.name); return true; }).filter(parameter => parameter.name !== 'form_instance' || originalParameters.some(original => original.name === 'form_instance')).map(parameter => { const original = originalParameters.find(p => p.name === parameter.name); return original && Object.hasOwn(original, 'default') ? { ...parameter, default: original.default } : parameter; });
|
|
247
|
+
const isForm = saved.component === 'Form' || saved.component === 'Performer';
|
|
248
|
+
if (isForm) {
|
|
249
|
+
result.form = {};
|
|
250
|
+
for (const key of formKeys)
|
|
251
|
+
if (spec[key] !== undefined)
|
|
252
|
+
result.form[key] = spec[key];
|
|
253
|
+
// Captured inputs are the authoring source; schema linking and question workers are derived on activation.
|
|
254
|
+
for (const key of ['prompt', 'prompt_es'])
|
|
255
|
+
if (resolvedFlow[key] !== undefined)
|
|
256
|
+
result.form[key] = resolvedFlow[key];
|
|
257
|
+
result.variables = Object.fromEntries(Object.entries(spec.extraVars || {}).map(([name, value]) => [name, variableDeclaration(value)]));
|
|
258
|
+
}
|
|
259
|
+
else if (spec.variables)
|
|
260
|
+
result.variables = spec.variables;
|
|
261
|
+
for (const [key, value] of Object.entries(spec))
|
|
262
|
+
if (!sharedKeys.includes(key) && !['extraVars', 'variables', 'helpers', 'safetyRevision'].includes(key) && !(isForm && formKeys.has(key)))
|
|
263
|
+
result[key] = value;
|
|
264
|
+
const out = rewrite(result);
|
|
265
|
+
// Helpers and bodies can reference other explicitly authored expressions as well.
|
|
266
|
+
for (const definition of Object.values(registry))
|
|
267
|
+
definition.body = definition.body.map(rewrite);
|
|
268
|
+
if (Object.keys(registry).length)
|
|
269
|
+
out.functions = registry;
|
|
270
|
+
JSON.stringify(out);
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
@@ -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
|
|
@@ -104,7 +105,7 @@ export function formFlow({ id, name, version, description, inputs, after = [], e
|
|
|
104
105
|
// FLOW parameters are paths only: the question is built here, as a SAY-style template, then passed by name
|
|
105
106
|
SET(`${id}_confirm_q`, 'form_confirm_q', textValue(confirm.question)),
|
|
106
107
|
SET(`${id}_confirm_q_es`, 'form_confirm_q_es', textValue(confirm.question_es || confirm.question)),
|
|
107
|
-
FLOW(`${id}_confirm`, 'confirm-form', 'call', { form: '{{form_instance}}', question: '{{form_confirm_q}}', question_es: '{{form_confirm_q_es}}', words: '{{form_confirmation.words}}', clarifications: '{{form_confirmation.clarifications}}', no_keys: '{{form_confirmation.no_keys}}', interrupts: '{{form_confirmation.interrupts}}', exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
|
|
108
|
+
FLOW(`${id}_confirm`, 'confirm-form', 'call', { form: '{{form_instance}}', question: '{{form_confirm_q}}', question_es: '{{form_confirm_q_es}}', phrases: '{{form_confirmation.phrases}}', words: '{{form_confirmation.words}}', clarifications: '{{form_confirmation.clarifications}}', no_keys: '{{form_confirmation.no_keys}}', interrupts: '{{form_confirmation.interrupts}}', exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
|
|
108
109
|
{ id: `${id}_confirmed`, type: 'CASE', branches: {
|
|
109
110
|
[`condition: (cargo.formConfirm || {})[form_instance] === 'changed'`]: FLOW(`${id}_again`, id, 'replace', { parent_form: '{{parent_form}}', result_input: '{{result_input}}', form_instance: '{{form_instance}}' }),
|
|
110
111
|
// NO: the declined flow takes the form's place, so the action below never runs
|
|
@@ -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_h.current && vb_response && !vb_known && !vb_h.invalid && vb_h.origin !== 'activation' && !vb_h.fromPending", FLOW('vb_read_response', 'read-form-response', 'call', { form: '{{vb_h.form}}', input: '{{vb_h.name}}' })),
|
|
309
|
+
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.',
|
|
@@ -396,7 +393,7 @@ const disambiguate = {
|
|
|
396
393
|
steps: [
|
|
397
394
|
WHEN('di_store_clear', 'Array.isArray(hits) && hits.length > 0', FLOW('di_store_hits', 'collect-input-accept', 'call', { hits: '{{hits}}' })),
|
|
398
395
|
SET('di_number', 'di_keys', `${KEYS_JS}(readings.length)`),
|
|
399
|
-
SET('di_build', 'di_choices', "readings.map(function (r, i) { var own = String(r.label + ' ' + r.label_es).toLowerCase().split(/\\s+/).filter(function (w) { return w.length > 3 && !readings.some(function (o, j) { return j !== i && String(o.label + ' ' + o.label_es).toLowerCase().split(/\\s+/).indexOf(w) > -1; }); }); return { key: 'r' + i,
|
|
396
|
+
SET('di_build', 'di_choices', "readings.map(function (r, i) { var own = String(r.label + ' ' + r.label_es).toLowerCase().split(/\\s+/).filter(function (w) { return w.length > 3 && !readings.some(function (o, j) { return j !== i && String(o.label + ' ' + o.label_es).toLowerCase().split(/\\s+/).indexOf(w) > -1; }); }); return { key: 'r' + i, phrases: [di_keys[i], r.label, r.label_es].concat(own) }; })"),
|
|
400
397
|
SET('di_said', 'di_value', "readings[0].pii ? '' : String(readings[0].value)"),
|
|
401
398
|
SET('di_question', 'di_q', "(di_value ? 'Is ' + di_value + ' your ' : 'Is that your ') + readings.map(function (r) { return r.label; }).join(' or your ') + '? ' + readings.map(function (r, i) { return (cargo.voice ? 'Press ' + di_keys[i] + ' or say ' : 'Say ') + r.label.toUpperCase(); }).join(', ') + '.'"),
|
|
402
399
|
SET('di_question_es', 'di_q_es', "(di_value ? '¿' + di_value + ' es su ' : '¿Eso es su ') + readings.map(function (r) { return r.label_es; }).join(' o su ') + '? ' + readings.map(function (r, i) { return (cargo.voice ? 'Presione ' + di_keys[i] + ' o diga ' : 'Diga ') + r.label_es.toUpperCase(); }).join(', ') + '.'"),
|
|
@@ -423,17 +420,17 @@ const disambiguate = {
|
|
|
423
420
|
const confirmForm = {
|
|
424
421
|
id: 'confirm-form', name: 'ConfirmForm', version: '1.0.0', scope: 'isolated',
|
|
425
422
|
description: "Worker: ask a form's confirmation (exact YES / NO; keys 1 and 2). A correction instead ('no, make it $40') is read against the form chain and stored, and the result is 'changed' so the form runs again; an unclear short answer is asked again, a long unrelated one is DISPATCHed. Result: cargo.formConfirm[form] = 'yes' | 'no' | 'changed'. Params: form, question(_es), exit_context(_es).",
|
|
426
|
-
parameters: ['form', 'question', 'question_es', 'exit_context', 'exit_context_es', 'words', 'interrupts', 'no_keys', 'clarifications'].map((n) => ({ name: n, type: ['words', 'interrupts', 'no_keys', 'clarifications'].includes(n) ? 'array' : 'string', description: n })),
|
|
427
|
-
variables: vars({ cf_presets: FIELD_PRESETS, cf_chain: [], cf_m: null, cf_current: null, cf_result: '', cf_prompt: '', cf_prompt_es: '', cf_words: 0, cf_tries: 0, words: [], clarifications: [], no_keys: ['2'], interrupts: [], cf_choices: [], cf_event: '', cf_amount: false, cf_questions: [], cf_provides: null, cf_skip_gate: '' }),
|
|
423
|
+
parameters: ['form', 'question', 'question_es', 'exit_context', 'exit_context_es', 'phrases', 'words', 'interrupts', 'no_keys', 'clarifications'].map((n) => ({ name: n, type: ['phrases', 'words', 'interrupts', 'no_keys', 'clarifications'].includes(n) ? 'array' : 'string', description: n })),
|
|
424
|
+
variables: vars({ cf_presets: FIELD_PRESETS, cf_chain: [], cf_m: null, cf_current: null, cf_result: '', cf_prompt: '', cf_prompt_es: '', cf_words: 0, cf_tries: 0, phrases: null, words: [], clarifications: [], no_keys: ['2'], interrupts: [], cf_choices: [], cf_event: '', cf_amount: false, cf_questions: [], cf_provides: null, cf_skip_gate: '' }),
|
|
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',phrases:['1'].concat(Array.isArray(phrases)?phrases:Array.isArray(words)?words:[]),exact:true},{key:'no',phrases:(Array.isArray(no_keys)?no_keys:['2']).concat(${JSON.stringify(ANSWER_WORDS.no)}),exact:true}].concat((Array.isArray(interrupts)?interrupts:[]).map(function(event){return {key:'event:'+event.key,phrases:event.phrases ?? event.words,exact:event.exact!==false};}))`),
|
|
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')"),
|
|
434
431
|
SET('cf_prompt_es', 'cf_prompt_es', "formInputPrompt(cargo,form,'__confirm',{question:question,question_es:question_es},{},'es')"),
|
|
435
432
|
SIDE('cf_feedback_consumed', "consumeFormFeedback(cargo,form,'__confirm')"),
|
|
436
|
-
FLOW('cf_ask', 'ask-choice', 'call', { amount: '{{cf_amount}}', question: '{{cf_prompt}}', question_es: '{{cf_prompt_es}}', choices: '{{cf_choices}}', accept_other: true, reask_long: true, digits: { min: 1, max: 1 }, exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
|
|
433
|
+
FLOW('cf_ask', 'ask-choice', 'call', { form_context: { form: '{{form}}', current: '__confirm' }, amount: '{{cf_amount}}', question: '{{cf_prompt}}', question_es: '{{cf_prompt_es}}', choices: '{{cf_choices}}', accept_other: true, reask_long: true, digits: { min: 1, max: 1 }, exit_context: '{{exit_context}}', exit_context_es: '{{exit_context_es}}' }),
|
|
437
434
|
SET('cf_event', 'cf_event', "(Array.isArray(interrupts)?interrupts:[]).filter(function(event){return cargo.choice==='event:'+event.key;}).map(function(event){return event.flow;})[0] || ''"),
|
|
438
435
|
WHEN('cf_interrupt', 'cf_event', FLOW('cf_event_flow', '{{cf_event}}', 'reboot', { form: '{{form}}', event: '{{cargo.choice}}', text: '{{cargo.choiceText}}' })),
|
|
439
436
|
SET('cf_build_chain', 'cf_chain', CHAIN_JS),
|
|
@@ -442,7 +439,7 @@ const confirmForm = {
|
|
|
442
439
|
SET('cf_provider_catalog', 'cf_provides', 'cargo.forms[form].providers'),
|
|
443
440
|
SET('cf_gate_policy', 'cf_skip_gate', "!cf_provides || !cf_provides.gate || [].concat(cf_provides.gate.verified || []).every(function(p){return !!formPath({cargo:cargo},p);}) ? 'true' : ''"),
|
|
444
441
|
SET('cf_current', 'cf_current', "cargo.forms[form].proposalPrompt ? {form:cargo.forms[form].parent,name:cargo.forms[form].proposalPrompt.input} : {form:form,name:''}"),
|
|
445
|
-
SET('cf_match', 'cf_m', "cargo.choice === 'yes' || cargo.choice === 'no' && pickChoice(cargo.choiceText, [{key:'no',
|
|
442
|
+
SET('cf_match', 'cf_m', "cargo.choice === 'yes' || cargo.choice === 'no' && pickChoice(cargo.choiceText, [{key:'no',phrases:Array.isArray(no_keys)?no_keys:['2'],exact:true}], false) === 'no' ? { hits: [], ambiguous: [], questions:[] } : readFormAnswer(cargo.choiceText, cf_chain, cf_current, '',cf_questions)"),
|
|
446
443
|
SET('cf_enrich', 'cf_m', "(function(m){m.hits=m.hits.map(function(h){return Object.assign({},h,{silent:true});});return m;})(enrichFormMatches(cf_m, cf_chain, form))"),
|
|
447
444
|
SET('cf_count_words', 'cf_words', "String(cargo.choiceText || '').split(/\\s+/).filter(function (w) { return /[a-záéíóúüñ]/i.test(w); }).length"),
|
|
448
445
|
WHEN('cf_question_fields', 'cf_m.questions.length > 0 && cf_m.hits.length > 0', FLOW('cf_question_accept', 'collect-input-accept', 'call', { hits: '{{cf_m.hits}}' })),
|
|
@@ -453,8 +450,8 @@ const confirmForm = {
|
|
|
453
450
|
'condition: cf_m.ambiguous.length > 0': FLOW('cf_ambiguous', 'disambiguate-input', 'call', { readings: '{{cf_m.ambiguous}}', hits: '{{cf_m.hits}}', remaining: '{{cf_m.remaining}}' }),
|
|
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
|
-
"condition: Array.isArray(clarifications) && pickChoice(String(cargo.choiceText || '').replace(/[?¿]/g,''),[{key:'clarify',
|
|
457
|
-
'condition: cf_words >= 3': yieldDispatch('cf_elsewhere', 'form', "'confirmation_not_matched'"),
|
|
453
|
+
"condition: Array.isArray(clarifications) && pickChoice(String(cargo.choiceText || '').replace(/[?¿]/g,''),[{key:'clarify',phrases:clarifications,exact:true}],false)==='clarify'": SET('cf_clarification', 'cf_result', "'clarification'"),
|
|
454
|
+
'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'"),
|
|
@@ -640,23 +637,23 @@ const provideQueuedData = {
|
|
|
640
637
|
};
|
|
641
638
|
// the menu's choices, built where the expression can see pd_menu (FLOW parameters are paths only)
|
|
642
639
|
provideData.variables.pd_menu_choices = { type: 'array', value: [] };
|
|
643
|
-
provideData.steps.splice(provideData.steps.findIndex((s) => s.id === 'pd_menu_q'), 0, SET('pd_menu_build', 'pd_menu_choices', "pd_menu.map(function (m, i) { return { key: m.key,
|
|
640
|
+
provideData.steps.splice(provideData.steps.findIndex((s) => s.id === 'pd_menu_q'), 0, SET('pd_menu_build', 'pd_menu_choices', "pd_menu.map(function (m, i) { return { key: m.key, phrases: [pd_mkeys[i], m.label || m.key, m.label_es || ''].filter(Boolean) }; })"));
|
|
644
641
|
// provider-menu: what next, after an answer — the catalog's actions, another fact, or done (owner MENU-1016 shape)
|
|
645
642
|
const providerMenu = {
|
|
646
643
|
id: 'provider-menu', name: 'ProviderMenu', version: '1.0.0', scope: 'isolated',
|
|
647
|
-
description: "Worker: after a provider answered, offer its menu (provides.menu: question(_voice)(_es) with {verb} / {name}; choices [{ key,
|
|
644
|
+
description: "Worker: after a provider answered, offer its menu (provides.menu: question(_voice)(_es) with {verb} / {name}; choices [{ key, phrases, flow, exact, set }]; done { phrases, say(_es) }). A fact or set named by its words is answered and the menu comes back; an action runs its flow (replace) after setting its `set` cargo fields; done says goodbye. Other phrases: DISPATCH. No phrases: asked once more, then 'anything else?'. Params: provides, retry.",
|
|
648
645
|
parameters: [{ name: 'provides', type: 'object', description: 'The provider catalog' }, { name: 'retry', type: 'string', description: "'1' on the re-ask" }],
|
|
649
646
|
variables: vars({ retry: '', pm_q: '', pm_q_es: '', pm_choices: [], pm_key: '', pm_keys: [], pm_close: false, pm_flow: '', pm_bye: '', pm_bye_es: '', pm_who: '', pm_sorry: '', pm_sorry_es: '' }),
|
|
650
647
|
steps: [
|
|
651
648
|
SET('pm_name', 'pm_who', NAME_JS),
|
|
652
649
|
SET('pm_question', 'pm_q', `(function () { ${RENDER_JS} var m = provides.menu; var t = cargo.voice && m.question_voice ? m.question_voice : m.question; return (retry === '1' ? "Sorry, I didn't catch that. " : '') + fill(t, {}, null, 'en', { name: pm_who, verb: cargo.verb || (cargo.voice ? 'say' : 'type') }); })()`),
|
|
653
650
|
SET('pm_question_es', 'pm_q_es', `(function () { ${RENDER_JS} var m = provides.menu; var t = cargo.voice && (m.question_voice_es || m.question_voice) ? (m.question_voice_es || m.question_voice) : (m.question_es || m.question); return (retry === '1' ? 'Disculpe, no le entendí. ' : '') + fill(t, {}, null, 'es', { name: pm_who, verb: cargo.verb_es || (cargo.voice ? 'diga' : 'escriba') }); })()`),
|
|
654
|
-
SET('pm_build', 'pm_choices', "provides.facts.concat(provides.sets || []).filter(function (f) { return Array.isArray(f.words) && f.words.length; }).map(function (f) { return { key: 'fact:' + f.key,
|
|
651
|
+
SET('pm_build', 'pm_choices', "provides.facts.concat(provides.sets || []).filter(function (f) { return Array.isArray(f.phrases ?? f.words) && (f.phrases ?? f.words).length; }).map(function (f) { return { key: 'fact:' + f.key, phrases: f.phrases ?? f.words }; }).concat((provides.menu.choices || []).map(function (c) { return { key: 'act:' + c.key, phrases: c.phrases ?? c.words, exact: c.exact === true }; })).concat(provides.menu.done ? [{ key: 'done', phrases: provides.menu.done.phrases ?? provides.menu.done.words, exact: true }] : [])"),
|
|
655
652
|
FLOW('pm_ask', 'ask-choice', 'call', { question: '{{pm_q}}', question_es: '{{pm_q_es}}', choices: '{{pm_choices}}', accept_other: true, digits: { min: 1, max: 1 }, exit_context: '{{provides.subject}}', exit_context_es: '{{provides.subject_es}}' }),
|
|
656
653
|
// A declared terminal phrase (for example "no thanks") may also fit a shorter action
|
|
657
654
|
// after courtesy stripping ("no"). Resolve only that overlap; fact ownership and the
|
|
658
655
|
// existing reserved done fallback retain their normal behavior.
|
|
659
|
-
SET('pm_take', 'pm_key', "(function(){var key=String(cargo.choice || '');if(key.indexOf('fact:')===0)return pickProviderQuestion(cargo.choiceText,pm_choices.filter(function(c){return c.key.indexOf('fact:')===0;}));if(key.indexOf('act:')===0 && provides.menu.done && pickChoice(cargo.choiceText,[{key:'terminal:done',
|
|
656
|
+
SET('pm_take', 'pm_key', "(function(){var key=String(cargo.choice || '');if(key.indexOf('fact:')===0)return pickProviderQuestion(cargo.choiceText,pm_choices.filter(function(c){return c.key.indexOf('fact:')===0;}));if(key.indexOf('act:')===0 && provides.menu.done && pickChoice(cargo.choiceText,[{key:'terminal:done',phrases:provides.menu.done.phrases ?? provides.menu.done.words,exact:true}],true)==='terminal:done')return 'done';return key;})()"),
|
|
660
657
|
SET('pm_fact_keys', 'pm_keys', "pm_key.indexOf('fact:') === 0 ? (function (k) { var s = (provides.sets || []).filter(function (x) { return x.key === k; })[0]; return s ? s.facts.slice() : [k]; })(pm_key.slice(5)) : []"),
|
|
661
658
|
SET('pm_closing', 'pm_close', "pm_keys.length > 0 && pm_keys.every(function (key) { var fact = provides.facts.find(function (f) { return f.key === key; }); return !!fact && fact.close === true; })"),
|
|
662
659
|
SET('pm_action_flow', 'pm_flow', "pm_key.indexOf('act:') === 0 ? (function (c) { if (c && c.set) { Object.keys(c.set).forEach(function (k) { cargo[k] = c.set[k]; }); } else { /* nothing to set */ } return c ? c.flow : ''; })((provides.menu.choices || []).filter(function (x) { return 'act:' + x.key === pm_key; })[0]) : ''"),
|
|
@@ -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
|
});
|