jsfe 1.7.5 → 1.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/forms/contracts.d.ts.map +1 -1
  2. package/dist/forms/contracts.js +12 -2
  3. package/dist/forms/flows.d.ts.map +1 -1
  4. package/dist/forms/flows.js +9 -10
  5. package/dist/forms/identity-flows.d.ts.map +1 -1
  6. package/dist/forms/identity-flows.js +4 -2
  7. package/dist/helpers/contact.d.ts +5 -1
  8. package/dist/helpers/contact.d.ts.map +1 -1
  9. package/dist/helpers/contact.js +10 -1
  10. package/dist/helpers/contextual-response.d.ts +10 -0
  11. package/dist/helpers/contextual-response.d.ts.map +1 -0
  12. package/dist/helpers/contextual-response.js +48 -0
  13. package/dist/helpers/form-state.d.ts +10 -2
  14. package/dist/helpers/form-state.d.ts.map +1 -1
  15. package/dist/helpers/form-state.js +33 -5
  16. package/dist/helpers/index.d.ts +5 -1
  17. package/dist/helpers/index.d.ts.map +1 -1
  18. package/dist/helpers/index.js +5 -3
  19. package/dist/helpers/match-inputs.d.ts.map +1 -1
  20. package/dist/helpers/match-inputs.js +59 -10
  21. package/dist/host/capabilities.d.ts.map +1 -1
  22. package/dist/host/capabilities.js +2 -1
  23. package/dist/host/index.d.ts +1 -0
  24. package/dist/host/index.d.ts.map +1 -1
  25. package/dist/host/index.js +1 -0
  26. package/dist/host/registry-composition.d.ts +16 -0
  27. package/dist/host/registry-composition.d.ts.map +1 -0
  28. package/dist/host/registry-composition.js +109 -0
  29. package/dist/index.d.ts +5 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +179 -29
  32. package/dist/runtime-identity.js +1 -1
  33. package/docs/copilot-reference.md +7 -0
  34. package/docs/development-release.md +20 -0
  35. package/docs/forms.md +53 -1
  36. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { validateContextualResponseStep } from './helpers/contextual-response.js';
1
2
  import { validateFlowRecovery } from './host/flow-recovery.js';
2
3
  import { ACTION_TOOLS } from './forms/action-tools.js';
3
4
  import { claimSessionAction, completeSessionAction } from './forms/session-actions.js';
@@ -1830,9 +1831,52 @@ function reportToolFailure(engine, tool, result) {
1830
1831
  logger.warn(`Tool ${tool.id}: failure report failed (${e.message}); result delivered unchanged`);
1831
1832
  }
1832
1833
  }
1833
- function validateToolArgs(tool, args) {
1834
+ // Flat parameter maps and object schemas describe named argument bags. Explicitly non-object
1835
+ // schemas retain their existing typed values, including a declared nullable root.
1836
+ function usesToolArgumentBag(schema) {
1837
+ const type = schema?.type;
1838
+ if (typeof type === 'string')
1839
+ return type === 'object';
1840
+ if (Array.isArray(type))
1841
+ return type.every((name) => name === 'object');
1842
+ if (schema === undefined || schema === null)
1843
+ return true;
1844
+ if (typeof schema !== 'object')
1845
+ return false;
1846
+ // A typeless JSON Schema can admit primitive/array/null roots. Only a clear flat field
1847
+ // map has the named-bag contract; do not infer it from a schema's missing `type`.
1848
+ const objectKeywords = ['properties', 'patternProperties', 'additionalProperties', 'propertyNames',
1849
+ 'items', 'additionalItems', 'contains', 'unevaluatedProperties', 'unevaluatedItems',
1850
+ 'allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else', 'enum', 'const', 'contentSchema'];
1851
+ if (Object.keys(schema).some((key) => key.startsWith('$') || objectKeywords.includes(key)))
1852
+ return false;
1853
+ return Object.values(schema).every((field) => field !== null && typeof field === 'object' && !Array.isArray(field));
1854
+ }
1855
+ function validateToolArgs(tool, supplied) {
1856
+ const declared = tool.parameters || tool.schema;
1857
+ let args = supplied;
1858
+ const objectBranch = Array.isArray(declared?.type) && declared.type.includes('object') &&
1859
+ supplied !== null && typeof supplied === 'object' && !Array.isArray(supplied);
1860
+ if (usesToolArgumentBag(declared) || objectBranch) {
1861
+ // A null/absent previous tool result supplies no named arguments. Never pass that value to
1862
+ // a positional adapter, or mutate a previous result while filling this tool's defaults.
1863
+ if (supplied !== null && supplied !== undefined && (typeof supplied !== 'object' || Array.isArray(supplied))) {
1864
+ throw new Error('Tool arguments must be an object');
1865
+ }
1866
+ if (supplied === null || supplied === undefined) {
1867
+ args = {};
1868
+ const properties = declared?.properties || (declared && !declared.type ? declared : {});
1869
+ for (const [key, property] of Object.entries(properties)) {
1870
+ if (property && typeof property === 'object' && property.default !== undefined) {
1871
+ // Only a newly normalized absent bag receives defaults. Preserve supplied objects
1872
+ // and their existing adapter/payload semantics; each new default owns its JSON copy.
1873
+ args[key] = JSON.parse(JSON.stringify(property.default));
1874
+ }
1875
+ }
1876
+ }
1877
+ }
1834
1878
  if (!tool.parameters)
1835
- return args; // No validation schema
1879
+ return args; // Preserve the existing schema validation policy.
1836
1880
  if (!ajv)
1837
1881
  return args; // ajv not available — skip validation
1838
1882
  const validate = ajv.compile(tool.parameters);
@@ -2121,8 +2165,8 @@ async function detectLanguage(input, engine) {
2121
2165
  }
2122
2166
  }
2123
2167
  // === FLOW EXECUTION ENGINE WITH ENHANCED ERROR HANDLING ===
2124
- async function isFlowActivated(input, engine, userId = 'anonymous') {
2125
- const result = await detectFlowWithParameters(input, engine);
2168
+ async function isFlowActivated(input, engine, userId = 'anonymous', detected) {
2169
+ const result = detected === undefined ? await detectFlowWithParameters(input, engine) : detected;
2126
2170
  if (result && result.flow) {
2127
2171
  const flow = result.flow;
2128
2172
  const parameters = result.parameters;
@@ -2173,6 +2217,16 @@ async function isFlowActivated(input, engine, userId = 'anonymous') {
2173
2217
  }
2174
2218
  return null;
2175
2219
  }
2220
+ function stampStepRecovery(step, currentFlowFrame, engine) {
2221
+ if (step.recovery !== undefined) {
2222
+ const resolved = Object.fromEntries(Object.entries(step.recovery).map(([key, value]) => [key, typeof value === 'string' && value.includes('{{') ? interpolateMessage(value, currentFlowFrame.contextStack, currentFlowFrame.variables, engine).trim() : value]));
2223
+ if (resolved.form === '' && resolved.flow === '') {
2224
+ delete resolved.form;
2225
+ delete resolved.flow;
2226
+ }
2227
+ engine.stampFlowRecovery(validateFlowRecovery(resolved));
2228
+ }
2229
+ }
2176
2230
  async function playFlowFrame(engine) {
2177
2231
  // Enhanced recursion protection using natural stack depth
2178
2232
  const stackDepth = getCurrentStackLength(engine);
@@ -2323,15 +2377,9 @@ async function playFlowFrame(engine) {
2323
2377
  const step = currentFlowFrame.flowStepsStack[currentFlowFrame.flowStepsStack.length - 1];
2324
2378
  const startTime = Date.now();
2325
2379
  try {
2326
- if (step.recovery !== undefined) {
2327
- const declaration = step.recovery;
2328
- const resolved = Object.fromEntries(Object.entries(declaration).map(([key, value]) => [key, typeof value === 'string' && value.includes('{{') ? interpolateMessage(value, currentFlowFrame.contextStack, currentFlowFrame.variables, engine).trim() : value]));
2329
- if (resolved.form === '' && resolved.flow === '') {
2330
- delete resolved.form;
2331
- delete resolved.flow;
2332
- }
2333
- engine.stampFlowRecovery(validateFlowRecovery(resolved));
2334
- }
2380
+ // A conditional handoff declares recovery only after a target has been selected.
2381
+ if (!(step.type === 'DISPATCH' && step.onResponse === 'continue'))
2382
+ stampStepRecovery(step, currentFlowFrame, engine);
2335
2383
  const result = await playStep(currentFlowFrame, engine);
2336
2384
  const duration = Date.now() - startTime;
2337
2385
  TransactionManager.addStep(currentFlowFrame.transaction, step, result, duration, 'success');
@@ -2359,6 +2407,12 @@ async function playFlowFrame(engine) {
2359
2407
  return result;
2360
2408
  }
2361
2409
  // DISPATCH ended every flow; processActivity routes this turn's input (see handleDispatchStep)
2410
+ if (step.type === 'DISPATCH' && step.onResponse === 'continue') {
2411
+ // ContinueCurrent retains the stack; a workflow replaces it; None hands off to the host.
2412
+ if (engine.pendingDispatchFrom !== null)
2413
+ return result;
2414
+ continue;
2415
+ }
2362
2416
  if (step.type === 'DISPATCH') {
2363
2417
  logger.info(`DISPATCH step executed, all flows ended; handing this turn's input back to intent detection`);
2364
2418
  return result;
@@ -2445,7 +2499,7 @@ async function playStep(currentFlowFrame, engine) {
2445
2499
  case 'END':
2446
2500
  return handleEndStep(currentFlowFrame);
2447
2501
  case 'DISPATCH':
2448
- return handleDispatchStep(currentFlowFrame, engine);
2502
+ return await handleDispatchStep(currentFlowFrame, engine);
2449
2503
  default:
2450
2504
  throw new Error(`Unknown step type: ${step.type}`);
2451
2505
  }
@@ -2741,7 +2795,7 @@ function enforceParameterTypes(flow, parameters) {
2741
2795
  return result;
2742
2796
  }
2743
2797
  /** The structured form of the intent-detection call, passed to aiCallback as its 4th argument. */
2744
- function buildDetectFlowRequest(input, lastChatTurn, flows) {
2798
+ function buildDetectFlowRequest(input, lastChatTurn, flows, responseContext) {
2745
2799
  const conversation = [];
2746
2800
  for (const entry of [lastChatTurn?.user, lastChatTurn?.assistant]) {
2747
2801
  if (entry && (entry.role === 'user' || entry.role === 'assistant')) {
@@ -2751,6 +2805,8 @@ function buildDetectFlowRequest(input, lastChatTurn, flows) {
2751
2805
  // absent, or a role the conversation cannot carry
2752
2806
  }
2753
2807
  }
2808
+ if (responseContext !== undefined)
2809
+ conversation.push({ role: 'assistant', content: responseContext });
2754
2810
  return {
2755
2811
  task: 'detect_flow',
2756
2812
  input: String(sanitizeInput(input)),
@@ -2776,8 +2832,8 @@ function buildDetectFlowRequest(input, lastChatTurn, flows) {
2776
2832
  * ({ flowName } / { parameters }). A stage-1 failure reaches the host as before; a stage-2 failure starts the flow
2777
2833
  * without its parameters (it asks for them) rather than losing the turn.
2778
2834
  */
2779
- async function detectFlowInTwoStages(input, engine, flows) {
2780
- const { input: cleanInput, conversation } = buildDetectFlowRequest(input, engine.lastChatTurn, []);
2835
+ async function detectFlowInTwoStages(input, engine, flows, responseContext) {
2836
+ const { input: cleanInput, conversation } = buildDetectFlowRequest(input, engine.lastChatTurn, [], responseContext);
2781
2837
  const stage1 = buildFlowStage(cleanInput, conversation, flows.map(f => ({ id: f.id, name: f.name, description: String(f.description ?? '') })));
2782
2838
  const reply1 = parseStageReply(await fetchAiResponse(stage1.llm.system, stage1.llm.user, engine.aiCallback, engine.aiTimeOut, stageSchema('detect_flow', stage1.llm.schema), stage1));
2783
2839
  const said = String(reply1.flowName ?? 'None');
@@ -2801,6 +2857,8 @@ async function detectFlowInTwoStages(input, engine, flows) {
2801
2857
  return { flow, parameters: enforceParameterEnums(flow, enforceParameterTypes(flow, ownParametersOnly(flow, given))) };
2802
2858
  }
2803
2859
  catch (error) {
2860
+ if (flow.id === '__jsfe_continue_current__' && responseContext !== undefined)
2861
+ throw error;
2804
2862
  logger.warn(`detectFlowWithParameters: stage 2 failed for "${flow.name}" (${error.message}) - the flow starts without its parameters`);
2805
2863
  return { flow, parameters: {} };
2806
2864
  }
@@ -2821,7 +2879,7 @@ export async function getFlowForInput(input, engine) {
2821
2879
  const result = await detectFlowWithParameters(input, engine);
2822
2880
  return result ? result.flow : null;
2823
2881
  }
2824
- export async function detectFlowWithParameters(input, engine) {
2882
+ export async function detectFlowWithParameters(input, engine, continuation, responseContext) {
2825
2883
  // CRITICAL: This function requires AI access via engine.aiCallback
2826
2884
  // Without AI, the engine cannot detect user intent and activate flows
2827
2885
  // Sessions would never be activated as no workflows could be triggered
@@ -2839,7 +2897,7 @@ export async function detectFlowWithParameters(input, engine) {
2839
2897
  }
2840
2898
  // Filter to only primary flows for AI intent detection
2841
2899
  const primaryFlows = flowsMenu.filter(flow => flow.primary === true);
2842
- const flowsForIntentDetection = primaryFlows.length > 0 ? primaryFlows : flowsMenu;
2900
+ const flowsForIntentDetection = (primaryFlows.length > 0 ? primaryFlows : flowsMenu).concat(continuation ? [continuation] : []);
2843
2901
  logger.debug(`Using ${flowsForIntentDetection.length} flows for intent detection (${primaryFlows.length} primary flows available)`);
2844
2902
  // A host start (ContextEntry.start) answers detection for this turn: that flow, with its arguments.
2845
2903
  if (engine.hostStart) {
@@ -2869,7 +2927,7 @@ export async function detectFlowWithParameters(input, engine) {
2869
2927
  return null;
2870
2928
  }
2871
2929
  if (engine.intentDetection === 'two-stage') {
2872
- return await detectFlowInTwoStages(input, engine, flowsForIntentDetection);
2930
+ return await detectFlowInTwoStages(input, engine, flowsForIntentDetection, responseContext);
2873
2931
  }
2874
2932
  else {
2875
2933
  // the original single call, below
@@ -2901,10 +2959,12 @@ export async function detectFlowWithParameters(input, engine) {
2901
2959
  </chat-history>\n\n`;
2902
2960
  }
2903
2961
  // Let AI errors (timeout, communication failures) propagate to the host
2904
- const request = buildDetectFlowRequest(input, engine.lastChatTurn, flowsForIntentDetection);
2962
+ if (responseContext !== undefined)
2963
+ context += `<current-response-context>\n${responseContext}\n</current-response-context>\n`;
2964
+ const request = buildDetectFlowRequest(input, engine.lastChatTurn, flowsForIntentDetection, responseContext);
2905
2965
  const aiResponse = await fetchAiTask(task, rules, context, input, flowsForIntentDetection, jsonSchema, engine.aiCallback, engine.aiTimeOut, request);
2906
2966
  if (aiResponse && aiResponse.flowName && aiResponse.flowName !== 'None' && aiResponse.flowName !== 'null') {
2907
- const flow = flowsMenu.find(flow => flow.name.toLowerCase() === aiResponse.flowName.toLowerCase() || flow.id === aiResponse.flowName);
2967
+ const flow = flowsMenu.concat(continuation ? [continuation] : []).find(flow => flow.name.toLowerCase() === aiResponse.flowName.toLowerCase() || flow.id === aiResponse.flowName);
2908
2968
  if (flow) {
2909
2969
  // Defensive: strip empty-string keys from AI-generated parameters.
2910
2970
  // AI occasionally emits { "": value } which would cascade into flow
@@ -3962,7 +4022,19 @@ function handleReturnStep(currentFlowFrame, engine) {
3962
4022
  // Return the evaluated value as string
3963
4023
  return String(returnValue);
3964
4024
  }
3965
- function handleDispatchStep(currentFlowFrame, engine) {
4025
+ async function handleDispatchStep(currentFlowFrame, engine) {
4026
+ const pending = currentFlowFrame.flowStepsStack[currentFlowFrame.flowStepsStack.length - 1];
4027
+ if (pending.onResponse === 'continue') {
4028
+ // Detection precedes any pop, declaration, transaction finalization or state reset.
4029
+ // A model error leaves this live continuation available to the caller's error policy.
4030
+ const matched = engine.dispatchIfMatched ? await engine.dispatchIfMatched(currentFlowFrame, pending) : false;
4031
+ if (!matched)
4032
+ currentFlowFrame.flowStepsStack.pop();
4033
+ return '';
4034
+ }
4035
+ return terminateForDispatch(currentFlowFrame, engine);
4036
+ }
4037
+ function terminateForDispatch(currentFlowFrame, engine) {
3966
4038
  // DISPATCH = forget every flow and treat THIS turn's input as if no flow had been active:
3967
4039
  // processActivity runs intent detection on the input the turn started with (never a flow
3968
4040
  // variable a step may have rewritten). It resets ALL engine flow state — every stack, the
@@ -4278,6 +4350,8 @@ async function generateToolArgs(schema, input, contextStack = [], flowFrame, eng
4278
4350
  return {};
4279
4351
  }
4280
4352
  logger.info(`Generating tool arguments for schema: ${schema.name || schema.title || 'unknown'}`);
4353
+ // Preserve raw null until validation can distinguish an absent bag from a supplied {}.
4354
+ // Undefined retains the existing flow-variable and AI inference path below.
4281
4355
  if (typeof input === 'object') {
4282
4356
  // the caller passed the arguments already built: used as given (keys only, never the values: they can be personal data)
4283
4357
  logger.info(`Using input object directly for args: ${Object.keys(input || {}).join(', ')}`);
@@ -5768,6 +5842,62 @@ async function processActivity(input, userId, engine) {
5768
5842
  logger.debug(`Current stack length: ${getCurrentStackLength(engine)}`);
5769
5843
  // A DISPATCH is consumed within the call that raised it; never carry one into another turn.
5770
5844
  engine.pendingDispatchFrom = null;
5845
+ // One routing decision for the original turn, shared by guarded and ordinary dispatch.
5846
+ let detected;
5847
+ let activatedThisTurn = false;
5848
+ let detectedResponseContext;
5849
+ let guardedRoutingFailed = false;
5850
+ const route = async (continuation, responseContext) => {
5851
+ if (detected === undefined) {
5852
+ detected = await detectFlowWithParameters(String(sanitizedInput), engine, continuation, responseContext);
5853
+ detectedResponseContext = responseContext;
5854
+ }
5855
+ else if (continuation?.parameters?.length && (responseContext !== detectedResponseContext || JSON.stringify(continuation.parameters) !== JSON.stringify(detected?.flow.parameters))) {
5856
+ throw new Error('A typed contextual response cannot reuse an incompatible routing decision this turn');
5857
+ }
5858
+ return detected;
5859
+ };
5860
+ engine.dispatchIfMatched = async (frame, step) => {
5861
+ if (activatedThisTurn && step.responseParameters === undefined && step.responseVariable === undefined)
5862
+ return false;
5863
+ if (engine.flowsMenu.some(flow => flow.name.toLowerCase() === 'continuecurrent' || flow.id.toLowerCase() === '__jsfe_continue_current__'))
5864
+ throw new Error('ContinueCurrent is reserved for contextual dispatch');
5865
+ let declaration;
5866
+ try {
5867
+ declaration = validateContextualResponseStep(step, engine.flowsMenu.find(flow => flow.id === frame.flowId));
5868
+ if (activatedThisTurn && declaration)
5869
+ throw new Error('Typed contextual response cannot classify after a flow activation this turn');
5870
+ }
5871
+ catch (error) {
5872
+ guardedRoutingFailed = true;
5873
+ throw error;
5874
+ }
5875
+ const context = interpolateMessage(step.responseContext, frame.contextStack, frame.variables, engine).trim();
5876
+ const continuation = { id: '__jsfe_continue_current__', name: 'ContinueCurrent', version: '1.0.0', primary: true, steps: [], ...(declaration ? { parameters: declaration.parameters } : {}), description: `The caller is responding to the requested ${context} or reports that the requested information is invalid, unknown or unavailable; datos incorrectos o inválidos, no lo sé, no lo tengo, no puedo dar el dato. Includes asking how to provide the requested information. Not a different service request or unrelated question; choose its workflow when offered, otherwise None for the host.` };
5877
+ let selected;
5878
+ try {
5879
+ selected = await route(continuation, context);
5880
+ }
5881
+ catch (error) {
5882
+ guardedRoutingFailed = true;
5883
+ throw error;
5884
+ }
5885
+ if (selected?.flow.id === continuation.id) {
5886
+ if (declaration)
5887
+ frame.variables[declaration.variable] = structuredClone(selected.parameters || {});
5888
+ return false;
5889
+ }
5890
+ stampStepRecovery(step, frame, engine);
5891
+ terminateForDispatch(frame, engine);
5892
+ if (!selected)
5893
+ return true; // Real host handoff: ordinary dispatch consumes the cached None below.
5894
+ engine.pendingDispatchFrom = null;
5895
+ engine.recordDispatch({ fromFlow: frame.flowName, matchedFlow: selected.flow.name });
5896
+ engine.clearFlowOutcome();
5897
+ activatedThisTurn = true;
5898
+ await isFlowActivated(String(sanitizedInput), engine, userId, selected);
5899
+ return true;
5900
+ };
5771
5901
  // Check if we're already in a flow (using new stack-of-stacks)
5772
5902
  if (getCurrentStackLength(engine) > 0) {
5773
5903
  logger.info(`\n=== [${new Date().toISOString()}] Flow Handling query: ${input} ===`);
@@ -5828,7 +5958,7 @@ async function processActivity(input, userId, engine) {
5828
5958
  logger.error(`Flow execution error: ${error.message}`);
5829
5959
  logger.info(`Stack trace: ${error.stack}`);
5830
5960
  // Clean up failed flow
5831
- if (getCurrentStackLength(engine) > 0) {
5961
+ if (!guardedRoutingFailed && getCurrentStackLength(engine) > 0) {
5832
5962
  const failedFrame = popFromCurrentStack(engine);
5833
5963
  TransactionManager.fail(failedFrame.transaction, error.message);
5834
5964
  }
@@ -5841,7 +5971,10 @@ async function processActivity(input, userId, engine) {
5841
5971
  const dispatchedFrom = engine.pendingDispatchFrom;
5842
5972
  engine.pendingDispatchFrom = null;
5843
5973
  try {
5844
- const activatedFlow = await isFlowActivated(String(sanitizedInput), engine, userId);
5974
+ const routed = await route();
5975
+ const activatedFlow = activatedThisTurn || routed?.flow.id === '__jsfe_continue_current__' ? null : await isFlowActivated(String(sanitizedInput), engine, userId, routed);
5976
+ if (activatedFlow)
5977
+ activatedThisTurn = true;
5845
5978
  if (dispatchedFrom !== null) {
5846
5979
  engine.recordDispatch({ fromFlow: dispatchedFrom, matchedFlow: activatedFlow ? activatedFlow.name : null });
5847
5980
  if (activatedFlow) {
@@ -5901,6 +6034,9 @@ async function processActivity(input, userId, engine) {
5901
6034
  // Re-throw as-is — let the host distinguish JSFEExecutionError from intent detection errors
5902
6035
  throw error;
5903
6036
  }
6037
+ finally {
6038
+ engine.dispatchIfMatched = null;
6039
+ }
5904
6040
  }
5905
6041
  // === WORKFLOW ENGINE CLASS ===
5906
6042
  // Words an expression may use that are not flow variables: JavaScript keywords, literals and the built-ins the
@@ -6069,6 +6205,8 @@ export class WorkflowEngine {
6069
6205
  * within the same call and routes the turn's input to intent detection. Never persisted.
6070
6206
  */
6071
6207
  pendingDispatchFrom = null;
6208
+ /** Internal per-turn routing callback; never serialized or retained across updateActivity calls. */
6209
+ dispatchIfMatched = null;
6072
6210
  // Command management for different application types (chat vs voice vs automation)
6073
6211
  enabledCommands;
6074
6212
  commandsEnabled;
@@ -7114,14 +7252,26 @@ export class WorkflowEngine {
7114
7252
  this._validateSubFlowStep(step, flowDef, state, opts, currentScope);
7115
7253
  break;
7116
7254
  case 'DISPATCH': {
7255
+ try {
7256
+ validateContextualResponseStep(step, flowDef);
7257
+ }
7258
+ catch (error) {
7259
+ state.errors.push(`DISPATCH step \"${step.id}\" in flow \"${flowDef.name}\": ${error.message}`);
7260
+ }
7117
7261
  // DISPATCH always routes the turn's own input — no value. It may declare the ending of the
7118
7262
  // flows it ends (`outcome` / `reason`, kept only when no flow matches).
7119
- const extra = Object.keys(step).filter(k => !['id', 'type', 'outcome', 'reason', 'recovery'].includes(k));
7263
+ const extra = Object.keys(step).filter(k => !['id', 'type', 'outcome', 'reason', 'recovery', 'onResponse', 'responseContext', 'responseParameters', 'responseVariable'].includes(k));
7120
7264
  if (extra.length > 0) {
7121
- state.errors.push(`DISPATCH step "${step.id}" in flow "${flowDef.name}" has invalid attribute(s) ${extra.map(k => `"${k}"`).join(', ')} - DISPATCH takes only "id", "outcome", "reason" and "recovery"`);
7265
+ state.errors.push(`DISPATCH step "${step.id}" in flow "${flowDef.name}" has invalid attribute(s) ${extra.map(k => `"${k}"`).join(', ')} - DISPATCH takes only "id", "outcome", "reason", "recovery", "onResponse" "responseContext", "responseParameters" and "responseVariable"`);
7122
7266
  }
7123
- else {
7124
- // well-formed
7267
+ else if (step.onResponse !== undefined && step.onResponse !== 'continue') {
7268
+ state.errors.push(`DISPATCH step "${step.id}" in flow "${flowDef.name}" onResponse must be "continue" when provided`);
7269
+ }
7270
+ else if (step.onResponse === 'continue' && (typeof step.responseContext !== 'string' || !step.responseContext.trim())) {
7271
+ state.errors.push(`DISPATCH step "${step.id}" in flow "${flowDef.name}" requires a non-empty responseContext for contextual dispatch`);
7272
+ }
7273
+ else if (step.responseContext !== undefined && step.onResponse !== 'continue') {
7274
+ state.errors.push(`DISPATCH step "${step.id}" in flow "${flowDef.name}" responseContext requires onResponse:"continue"`);
7125
7275
  }
7126
7276
  break;
7127
7277
  }
@@ -1 +1 @@
1
- export const JSFE_RUNTIME_FINGERPRINT = "sha256:80dad4930b16f70b08ade26e77712eea29dfed68a582f5b6b69906a3a8becb76";
1
+ export const JSFE_RUNTIME_FINGERPRINT = "sha256:b4e1b19b303f3468647ee0f97a03a12400204ab8e3936e5febcd4d22b2a5b5ae";
@@ -49,6 +49,13 @@ END — Returns from the current flow only, resuming its caller at the step afte
49
49
 
50
50
  DISPATCH — Ends every flow (all stacks, and any SAY output not yet delivered) and routes the user's input for THIS turn through intent detection, exactly as if no flow had been active: a matching flow starts in the same turn, otherwise the host AI/RAG answers. Takes an id and optionally outcome/reason (no value): the ended flows' outcome reaches the host only when no flow matches. Use it right after a SAY-GET whose answer may really be a new request — e.g. the "default" branch of a menu's CASE, or the answer to "Anything else?" — so the user can move from flow to flow.
51
51
 
52
+ Conditional handoff — `DISPATCH` may declare `onResponse: "continue"` and a non-empty `responseContext` describing the current requested information. This scoped routing offers a reserved `ContinueCurrent` disposition alongside the primary workflows and `None`: a response (including invalid data or clarification) keeps the live continuation and executes the following authored recovery steps; a named workflow replaces the stacks; an unrelated request with no workflow (`None`) hands off to the host as usual. The decision precedes termination, recovery and outcome stamping, is reused once, and never restores a snapshot. Detection errors propagate with the continuation intact. Ordinary DISPATCH behavior is unchanged when the option is absent.
53
+
54
+ Typed contextual response (reviewed, unreleased runtime) — pair `responseParameters: [...]` (primitive `string`/`boolean`/`number`/`integer` parameter descriptors; contextual v1 rejects `object`, `array`, and `jsonSchema`) with `responseVariable: 'response'` (an object variable declared in that flow). The existing extraction stage supplies normalized parameters only when `ContinueCurrent` is chosen; JSFE binds a cloned object before continuing. A named primary or `None` never writes that variable. Missing fields remain missing: the caller must validate completeness and collect/re-ask, never treat the disposition as confirmation or effect authorization. Typed model errors preserve the live step and previous object. Conflicting typed decisions within one turn fail closed.
55
+
56
+ All explicit contextual steps pass the resolved `responseContext` into detection and any extraction stage without mutating `lastChatTurn`. Native builders derive `jsfe:contextual-responses:v1` and its `contextualResponseProtocol() === 1` entry guard for typed steps; a matched runtime/helper registry is required, with no host flag that can enable unsupported support. Ordinary DISPATCH remains unchanged. See [Typed contextual responses](forms.md#typed-contextual-responses) for the complete contract and a minimal example.
57
+
58
+
52
59
  Declared outcome — the step that ends a flow (RETURN, END, DISPATCH or a final SAY) may carry outcome and reason (both accept {{}}): "unresolved" (the user's need was not met; the flow's transaction is marked failed), "deflected" (a decoy flow absorbed a false-positive intent by design), "resolved" (informational). An outcome that interpolates to empty declares nothing. The host reads it to recover from an unresolved ending.
53
60
 
54
61
  ## Cargo — Session-Persistent State
@@ -43,3 +43,23 @@ The local candidate corrects input ownership for incidental known-parent choices
43
43
  Tenant integration resolves a valid canonical case before compatibility routing, builds CRM verification text from the same contact snapshot as payload flags, and handles account-menu bare NO through the existing provider action contract. Intent probes fail execution errors independently of expected intent, reject malformed/empty runs, and retain a bilingual synthetic corpus. The new corpus is not a reconstruction of the historical uncommitted production replay.
44
44
 
45
45
  Accept the same immutable tarball in isolated matched host/tenant installs. Run every engine suite and `npm run test:accept`, including the original journeys on both flow sets; `npm test` alone runs the curacao suites in legacy mode. Add host preprocessing end-reason checks to distinguish a closing question from a farewell, and exercise actual tool-call counts, payloads, reentry and fresh consent. Live model probes are separate from hermetic acceptance and retain execution failures as failures. Release authorization was granted after the local review. Publish the accepted runtime as 1.7.5, pin both consumers, deploy the dev host, then activate the matched shared and tenant definitions in the three dev configs. Production deployment remains a separate action.
46
+
47
+ ## 1.7.6 reviewed input recovery and data ownership
48
+
49
+ The release preserves complete FORM voice answers before profile normalization, adds opt-in narrative evidence ownership and dependency-aware choice handling, and resumes a changed opted-in ancestor through its live owner. Contextual literal email reading remains opt-in. Absent/null named tool argument bags normalize without changing supplied object payloads or nullable roots.
50
+
51
+ Contextual DISPATCH is opt-in through `onResponse:"continue"` and `responseContext`. A scoped ContinueCurrent decision runs authored bounded recovery without terminating the owner; a registered workflow replaces it once; None hands an unrelated request to the host. Detection precedes termination and outcome/recovery stamping. Model errors do not authorize a switch, reserved disposition names cannot collide with registry names, and ordinary DISPATCH is unchanged. Both the native and canonical legacy contact collectors opt in. Confirmation, action persistence and storage encoding contracts are unchanged.
52
+
53
+ Reviewed acceptance: all 81 engine test files, 121 legacy and 121 native tenant suites; all 622 deterministic and 622 production-model primary journeys spanning 17 primaries and 166 applicable paths. Full-day replay retains 2,325 conversations and 8,543 original turns with no engine exceptions. Nine extraction deadlines and one empty Shopify cleanup response remain visible in model-health evidence; the extraction cases rechecked cleanly with production model redundancy. Shared Shopify's safe original-input fallback remains separately scoped. Unknown backend fixtures are diagnostic, never customer-success evidence.
54
+
55
+ Owner authorized publication, exact consumer pins, dev host deployment and matched shared/native flow activation on all three dev configs with session-only action persistence. Production deployment/activation is not part of this release authorization. Publish/install the accepted package before activating its matched definitions.
56
+
57
+ ## 1.7.7 typed contextual responses and explicit registry composition
58
+
59
+ Typed contextual DISPATCH binds canonical primitive fields only after ContinueCurrent, using the active question in both intent stages. Named/None handoffs do not commit old input. Routing/extraction failures preserve pending ownership; a second incompatible decision in one turn fails closed. The capability and its strict entry guard are explicit; existing ordinary DISPATCH remains unchanged.
60
+
61
+ `jsfe/host` exports opt-in `composeRegistries` for independently compiled modules. It clones plain JSON declarations, deduplicates identical same-ID definitions, and rejects conflicts and case-insensitive ID/name aliases. Array and object property order remain execution data. Existing engine loaders do not compose implicitly.
62
+
63
+ Reviewed Shopify acceptance covers 47 native definitions, three primary providers, 639 domain assertions, 88 production-model synthetic journeys (336 turns), both 127-suite tenant modes, and 83 SDK test files. Customer tools remain local stubs. The 12 retained nonprimary legacy definitions serve saved continuations only; native host admission rejects known fresh legacy references and incomplete native bundles.
64
+
65
+ Owner authorized publication, exact consumer pins, dev host deployment, and matched shared/native Shopify activation for all three dev tenant configurations with explicit session-only action persistence. Production deployment/activation is outside this authorization. Match runtime, system, tenant and Shopify assets; do not enable native Shopify on the older production system registry.
package/docs/forms.md CHANGED
@@ -41,7 +41,13 @@ A batch retains independent valid fields if another field fails. Dependent early
41
41
 
42
42
  Resolve overlapping evidence in this order: current field, one matching field at the nearest owning scope, then ancestors. Multiple competing claims at the same applicable scope are clarified. Independent spans fill independent fields. Typed evidence beats an unconstrained text fallback. A noncurrent, already-filled choice mentioned incidentally in the current text answer does not displace that answer; a whole-answer repetition (including courtesy) remains a claim to that choice. Explicit new choices and structured data remain eligible out of order. Resolve losing fallback evidence before computing overlapping groups, so one whole-answer text span cannot make independent email/phone clauses ambiguous. `confirm_against` deliberately retains paired interpretations and overrides ordinary priority.
43
43
 
44
- The common loop asks the first ready missing required input, skips accepted data, unwinds inapplicable children and blocks unresolved prerequisites. A context service may use `stop` and `close_on_stop:true` to close itself without handing a value to its parent. With `resume_on_parent_change:true`, an accepted owner correction closes the stale context service and resumes the same owned form with its retained progress, requiring a fresh confirmation. `RETURN` ends the entire engine transaction; ordinary worker completion uses `END`.
44
+ FORM collectors preserve the original answer by default (`as_spoken:true`), including on voice channels. Their declared profile readers normalize typed evidence and match out-of-order fields before validation; question-specific voice cleanup must not discard other fields first. Explicit `as_spoken:false` remains available for a field that deliberately needs that cleanup. Direct `SAY-GET` and ordinary `ask-choice` defaults remain unchanged.
45
+
46
+ For an open rationale or description, opt into `profile:{kind:'text',narrative:true}`. The current narrative retains the full answer while independently shaped phone/email fields spend only their own spans. A structured-only number or address does not fill the rationale. Incidental ancestor choices and same-form choices listed in the requested field’s `reset_on` dependencies are context; a whole-answer declared choice or a bounded explicit correction such as “actually insurance” or “en realidad seguro” can still revise the ancestor. Other sibling choices remain independently collectable, including in compound answers. Whole-answer choices, explicit corrections, independently typed fields and explicit `confirm_against` ambiguity retain their normal behavior. A choice field may also opt into `narrative:true` when its answer commonly includes surrounding explanation; a valid current selection then owns that explanation without changing another discriminator from an incidental word. This does not infer an unmatched choice or bypass its validator. Ordinary text profiles keep their existing structured-input precedence.
47
+
48
+ Narrative collection reads email fields in explicit literal mode: a complete visible `owner@example.com` token stays that exact recipient, even inside prose. The standalone API `readEmail(text,{literal:true})` and `profile:{kind:'email',literal:true}` offer the same behavior. Different visible addresses fail closed; with no visible email token, spoken/spelled parsing remains available. Default `readEmail(text)` is unchanged, including joining intentional local-name fragments such as “Maria jose@gmail.com”. Use the explicit contextual mode when surrounding prose must not become part of the recipient.
49
+
50
+ The common loop asks the first ready missing required input, skips accepted data, unwinds inapplicable children and blocks unresolved prerequisites. A context service may use `stop` and `close_on_stop:true` to close itself without handing a value to its parent. With `resume_on_parent_change:true`, an accepted owner correction closes the stale context branch and resumes the highest changed opted-in ancestor with its retained progress, requiring a fresh confirmation. Nested contexts cannot return through obsolete callback tails or restore an old draft or action token; unrelated tasks remain intact. `RETURN` ends the entire engine transaction; ordinary worker completion uses `END`.
45
51
 
46
52
  Optional follow-ups may declare `incomplete_outcome:{outcome:'resolved',reason:'payment_made'}` to preserve an already completed task’s outcome when collection cannot finish or the user leaves. Accepted outcome values are `resolved`, `unresolved` and `deflected`, with a nonempty reason. A reusable form may instead use `incomplete_outcome:{from:'completed_outcome'}` with a declared object parameter; its runtime value must pass the same validation. The nearest actual owned ancestor supplies a fallback to a child. Another task’s outcome never does. The policy covers missing input specifications, blocked dependencies, exhausted validation/retries and unmatched collection/confirmation dispatch; it does not complete missing inputs or authorize effects. Omit it for ordinary required forms: contextual yields are pending, while actual validation or service failures remain unresolved.
47
53
 
@@ -173,3 +179,49 @@ Generation failures, stale artifacts, empty suite selections, crashed suites and
173
179
  ## Provider menu terminal intent
174
180
 
175
181
  Provider menus keep terminal phrases distinct from neutral menu answers. If an answer selects an action only because courtesy normalization also matches a shorter phrase, an explicitly declared whole-answer `menu.done.words` phrase takes its terminal meaning. For example, a neutral action keyed by “no” can ask what else the caller needs while “no thanks” remains terminal. Fact requests retain their existing priority and the existing done/deferral fallback is preserved. Reuse provider-menu actions and shared phrase renderers instead of adding tenant-specific parsing to the engine.
182
+
183
+ ### Identification handoff on an unmapped answer
184
+
185
+ The shared contact/account collector uses contextual `DISPATCH` (`onResponse: "continue"`, `responseContext`) before abandoning an unmapped conversational answer. The current input request is offered as a scoped `ContinueCurrent` disposition alongside the primary flows. A classified response retains the live continuation and enters the existing retry/options menu, where a complete identifier can still be supplied. A supported new intent replaces the workflow; an unrelated request without a workflow hands off to the host. This is a decision before state mutation, not a session snapshot restore. Ordinary FORM yields and exhausted retries retain their existing behavior; confirmations and action guards are unchanged.
186
+
187
+
188
+ ### Typed contextual responses
189
+
190
+ The reviewed contextual-response extension is **unreleased**. Use its matched JSFE runtime, builders and `STANDARD_FUNCTIONS` registry; do not infer support from a package version label. Ordinary `DISPATCH` remains unchanged. Every explicit contextual `DISPATCH` (`onResponse: 'continue'`) passes its resolved `responseContext` to workflow detection and to parameter extraction when that stage runs, including when another primary is selected. The context is an additional assistant turn for this decision; it does not overwrite `lastChatTurn` or restore a session snapshot. Supply a concise description of the current request and the data actually offered.
191
+
192
+ A contextual step may additionally declare **both** `responseParameters` and `responseVariable`. `responseParameters` is a nonempty array of canonical flow parameter descriptors (`name`, `description`, optional `type` and string `enum`). Contextual response v1 accepts only `string` (the default), `boolean`, `number`, and `integer` fields; it rejects `object`, `array`, and `jsonSchema`. Ordinary flow parameter support is unchanged. Derive it from the provider's existing parameter catalog instead of maintaining a second semantic vocabulary. `responseVariable` must name an object variable declared in the same flow: a safe identifier, never a cargo path or reserved engine variable.
193
+
194
+ When detection chooses `ContinueCurrent`, JSFE extracts those parameters through the existing parameter stage, normalizes their declared types/enums, drops unoffered fields, and binds a cloned object to that variable before the following authored steps run. The live stack, transaction ownership, outcome and recovery declaration remain intact. A named primary replaces the continuation normally; `None` hands off normally. Neither disposition writes the response variable.
195
+
196
+ ```js
197
+ import { defineWorker } from 'jsfe/forms';
198
+
199
+ const replyParameters = [
200
+ { name: 'asked', type: 'string', enum: ['stock', 'price', 'search'],
201
+ description: 'An existing stock/price fact, or a new search with changed features.' },
202
+ { name: 'refinement', type: 'string',
203
+ description: 'Changed features for the previously shown products; otherwise absent.' },
204
+ ];
205
+
206
+ const reply = defineWorker({
207
+ id: 'product-reply', name: 'ProductReply',
208
+ contract: { role: 'worker', summary: 'Interpret a question about shown products' },
209
+ variables: {
210
+ answer: { type: 'string', value: '' },
211
+ response: { type: 'object', value: null },
212
+ },
213
+ steps: [
214
+ { id: 'ask', type: 'SAY-GET', variable: 'answer', asSpoken: true,
215
+ value: 'Ask about these products, or describe the features you want.' },
216
+ { id: 'read', type: 'DISPATCH', onResponse: 'continue',
217
+ responseContext: 'The current product query is {{cargo.productQuery}}. Questions about its shown results or changed product features continue this task.',
218
+ responseParameters: replyParameters, responseVariable: 'response' },
219
+ { id: 'result', type: 'SET', variable: 'noop',
220
+ value: '(cargo.productReply = response, true)' },
221
+ ],
222
+ });
223
+ ```
224
+
225
+ Builders automatically declare the intrinsic requirement `jsfe:contextual-responses:v1` and add a fail-closed entry guard requiring `contextualResponseProtocol() === 1`. This is runtime support, not a host permission or a new configuration switch. Hosts still run capability admission; unsupported intrinsic versions cannot be enabled by supplying a boolean. An older helper registry fails before tenant steps execute.
226
+
227
+ Missing or invalid extracted parameters may yield an empty object. The caller must check the required fields and use its normal bounded collection/retry policy; choosing `ContinueCurrent` is not evidence that every requested value exists and never authorizes an effect. A model exception during typed continuation detection or extraction preserves the pending step and prior response object. One decision is reused per turn: incompatible typed context/schema reuse fails closed, as does reaching a typed classification after another workflow has already been activated that turn. Ordinary and untyped dispatch retain their prior routing/cache semantics.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "1.7.5",
3
+ "version": "1.7.7",
4
4
  "description": "TypeScript workflow engine for conversational/automation apps: multi-flow orchestration, interrupt/resume, stack-based control, robust errors, and flexible tool/REST integration.",
5
5
  "license": "MIT",
6
6
  "author": "Ron Pinkas",