jsfe 1.40.2 → 1.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,6 +2,8 @@ import { compileFlowDeclarations, flowSetData } from './forms/declarations.js';
2
2
  import { findFlowTraps, formatFlowTrap } from './forms/flow-traps.js';
3
3
  import { compileNamedFunctions } from './helpers/named-functions.js';
4
4
  import { closeFormInstance } from './helpers/form-state.js';
5
+ import { isGlobalExit } from './helpers/answer.js';
6
+ import { callerTextNumber } from './helpers/contact.js';
5
7
  import { storedSession, restoreStoredSession } from './helpers/stored-session.js';
6
8
  import { validateContextualResponseStep, validateResponseParameters } from './helpers/contextual-response.js';
7
9
  import { validateFlowRecovery } from './host/flow-recovery.js';
@@ -2976,9 +2978,9 @@ async function detectFlowInTwoStages(input, engine, flows) {
2976
2978
  * when the host says `answers` is the default because no option cleared its cut (`fallback: true`); an answer
2977
2979
  * without that flag (a text model's pick, or a host that does not send it) is a confident one.
2978
2980
  */
2979
- async function rankReply(input, engine, question, choices = [], reasonFor = '') {
2981
+ async function rankReply(input, engine, question, choices = [], reasonFor = '', concern = '') {
2980
2982
  const { input: cleanInput, conversation } = buildDetectFlowRequest(input, engine.lastChatTurn, []);
2981
- const request = buildReplyRank(cleanInput, conversation, question, choices, { reasonFor });
2983
+ const request = buildReplyRank(cleanInput, conversation, question, choices, { reasonFor, concern });
2982
2984
  const reply = parseStageReply(await fetchAiResponse(request.llm.system, request.llm.user, engine.aiCallback, engine.aiTimeOut, stageSchema('rank_reply', request.llm.schema), request));
2983
2985
  const option = String(reply.option ?? '');
2984
2986
  if (!request.options.includes(option))
@@ -4194,6 +4196,73 @@ async function handleDispatchStep(currentFlowFrame, engine) {
4194
4196
  }
4195
4197
  return terminateForDispatch(currentFlowFrame, engine);
4196
4198
  }
4199
+ /**
4200
+ * The global exit (owner 2026-11-11). The flow that answers a caller who exits, after every flow has ended: the
4201
+ * system set's `global-exit`, or the tenant flow that `wraps` it. It receives the outcome in force before the flows ended, so
4202
+ * a caller who leaves after being served is thanked. Null when the set has neither a wrapper nor `contact-support`: the generic reply answers.
4203
+ */
4204
+ export const GLOBAL_EXIT_FLOW = 'global-exit';
4205
+ function globalExitStart(engine) {
4206
+ const menu = engine.flowsMenu || [];
4207
+ const base = menu.find(f => f.id === GLOBAL_EXIT_FLOW);
4208
+ const wrapper = base ? menu.find(f => f.wraps === base.id || f.wraps === base.name) : undefined;
4209
+ // The default reboots to the set's `contact-support`; a set without one keeps the generic reply (a FLOW to a missing flow is skipped).
4210
+ const flow = wrapper || (base && menu.some(f => f.id === 'contact-support') ? base : undefined);
4211
+ return flow ? { flow: flow.id, arguments: { exit_outcome: outcomeInForce(engine)?.outcome || '' } } : null;
4212
+ }
4213
+ /**
4214
+ * Keypad 9 switches a call to text (owner 2026-10-31, global since 1.42.0), as keypad 8 changes the language in the host: a call,
4215
+ * the whole answer "9", a caller number that can take texts, the set has `switch-to-text`, and the waiting question neither
4216
+ * declares a choice for 9 nor asks for an amount (ask-choice `amount`). The flows end and `switch-to-text` starts.
4217
+ */
4218
+ const TEXT_SWITCH_FLOW = 'switch-to-text';
4219
+ function textSwitchStart(input, frame, engine) {
4220
+ const cargo = engine.cargo || {};
4221
+ if (!cargo.voice || String(input ?? '').trim().replace(/[.,!?;:]+$/, '') !== '9')
4222
+ return null;
4223
+ else if (!callerTextNumber(cargo))
4224
+ return null;
4225
+ else if (!(engine.flowsMenu || []).some(f => f.id === TEXT_SWITCH_FLOW))
4226
+ return null;
4227
+ else if (frame?.variables?.amount === true || frame?.variables?.amount === 'true')
4228
+ return null;
4229
+ else if (declaresChoiceFor(frame, p => String(p).trim() === '9'))
4230
+ return null;
4231
+ else
4232
+ return { flow: TEXT_SWITCH_FLOW, arguments: {} };
4233
+ }
4234
+ /** Whether the question waiting in this frame declares a choice (its key or a phrase) that this test accepts. */
4235
+ function declaresChoiceFor(frame, test) {
4236
+ const choices = frame?.variables?.choices;
4237
+ return Array.isArray(choices) && choices.some((c) => c && [c.key, ...(Array.isArray(c.phrases) ? c.phrases : [])].some(p => typeof p === 'string' || typeof p === 'number' ? test(String(p)) : false));
4238
+ }
4239
+ /** Whether the question waiting in this frame declares its own choice for an exit word: that choice takes the answer. */
4240
+ function declaresExitChoice(frame) {
4241
+ return declaresChoiceFor(frame, p => isGlobalExit(p));
4242
+ }
4243
+ /** Every flow ends (finalized, audited with `reason`), with no outcome declared: the flow started next declares its own. */
4244
+ function endFlowsFor(currentFlowFrame, engine, reason) {
4245
+ while (engine.flowStacks.length > 0) {
4246
+ const poppedStack = engine.flowStacks.pop();
4247
+ for (const flow of poppedStack || []) {
4248
+ finalizeFlowTransaction(engine, flow, 'return');
4249
+ auditLogger.logFlowExit(flow.flowName, currentFlowFrame.userId, flow.transaction.id, reason);
4250
+ }
4251
+ }
4252
+ initializeFlowStacks(engine);
4253
+ }
4254
+ /** The whole answer is the global exit: every flow ends as a withdrawal does, before any reader or the reply ranker sees it. */
4255
+ function terminateForExit(currentFlowFrame, engine) {
4256
+ currentFlowFrame.declaredOutcome = { outcome: 'user_aborted', reason: 'exit_requested' };
4257
+ while (engine.flowStacks.length > 0) {
4258
+ const poppedStack = engine.flowStacks.pop();
4259
+ for (const flow of poppedStack || []) {
4260
+ finalizeFlowTransaction(engine, flow, 'return');
4261
+ auditLogger.logFlowExit(flow.flowName, currentFlowFrame.userId, flow.transaction.id, 'exit_requested');
4262
+ }
4263
+ }
4264
+ initializeFlowStacks(engine);
4265
+ }
4197
4266
  /** A withdrawn request ends as a RETURN does: the DISPATCH step is consumed and every flow finalizes and ends. */
4198
4267
  function terminateForAbort(currentFlowFrame, engine) {
4199
4268
  const step = currentFlowFrame.flowStepsStack.pop();
@@ -5482,6 +5551,10 @@ function getEngineSessionVariables(engine, contextStack) {
5482
5551
  // tenant default (or another session's language): Spanish prompts, then an English RETURN built
5483
5552
  // with `language === 'es'` (prod 2026-09-24, a receipt reply).
5484
5553
  sessionVars.language = engine.getSessionLanguage() || engine.language;
5554
+ // $outcome: the declared outcome in force for the running flow (see FlowOutcome) — its own declaration, else the
5555
+ // nearest one among the flows that called it on this stack; null when none declared. A flow that starts declares
5556
+ // nothing, and a called flow's declaration ends with it, so the caller it resumes reads its own again.
5557
+ sessionVars.$outcome = outcomeInForce(engine);
5485
5558
  // Special function-like variables
5486
5559
  sessionVars['currentTime()'] = new Date().toISOString();
5487
5560
  // Add global variables if available
@@ -5494,6 +5567,20 @@ function getEngineSessionVariables(engine, contextStack) {
5494
5567
  }
5495
5568
  return sessionVars;
5496
5569
  }
5570
+ // The nearest declared outcome on the current stack, from the running flow down to the first flow of the stack.
5571
+ function outcomeInForce(engine) {
5572
+ const stack = getCurrentStack(engine);
5573
+ for (let i = stack.length - 1; i > -1; i--) {
5574
+ const declared = stack[i].declaredOutcome;
5575
+ if (declared) {
5576
+ return { outcome: declared.outcome, reason: declared.reason, flowName: stack[i].flowName };
5577
+ }
5578
+ else {
5579
+ continue;
5580
+ }
5581
+ }
5582
+ return null;
5583
+ }
5497
5584
  /**
5498
5585
  * Create evaluation context with all available variables for simplified evaluator
5499
5586
  */
@@ -5975,6 +6062,8 @@ async function processActivity(input, userId, engine) {
5975
6062
  let ranked = null;
5976
6063
  // `abort` is a RETURN: every flow ends and this is the turn's reply.
5977
6064
  let abortReply = null;
6065
+ // The global exit's flow, started once every flow has ended (a withdrawal, or *, EXIT, QUIT or SALIR).
6066
+ let exitStart = null;
5978
6067
  let guardedRoutingFailed = false;
5979
6068
  let preDetected = undefined;
5980
6069
  engine.dispatchIfMatched = async (frame, step) => {
@@ -6026,8 +6115,10 @@ async function processActivity(input, userId, engine) {
6026
6115
  let also;
6027
6116
  // A reason question names what the caller does not want; empty (or no attribute) ranks the reply generically.
6028
6117
  const reasonFor = declaration?.reasonFor ? interpolateMessage(declaration.reasonFor, frame.contextStack, frame.variables, engine).trim() : '';
6118
+ // A question whose process is described (a form's user_description) offers `concern`; empty offers nothing more.
6119
+ const concern = declaration?.concern ? interpolateMessage(declaration.concern, frame.contextStack, frame.variables, engine).trim() : '';
6029
6120
  try {
6030
- ({ option, confident, also } = await rankReply(String(sanitizedInput), engine, question, choices, reasonFor));
6121
+ ({ option, confident, also } = await rankReply(String(sanitizedInput), engine, question, choices, reasonFor, concern));
6031
6122
  }
6032
6123
  catch (error) {
6033
6124
  guardedRoutingFailed = true;
@@ -6112,6 +6203,16 @@ async function processActivity(input, userId, engine) {
6112
6203
  logger.info(`Contextual DISPATCH in '${frame.flowName}': the reply answers the current question; the flow continues`);
6113
6204
  return false;
6114
6205
  }
6206
+ else if (option === 'concern') {
6207
+ // The caller objects to or misunderstands what the process does: nothing is extracted and no flow moves; the flow
6208
+ // reads `concern: true`, says what the process does and how to cancel, and asks again.
6209
+ ranked = 'concern';
6210
+ if (declaration)
6211
+ frame.variables[declaration.variable] = declaration.parameters.length ? { concern: true } : { key: '', concern: true };
6212
+ else { /* no typed response: the flow reads the reply itself */ }
6213
+ logger.info(`Contextual DISPATCH in '${frame.flowName}': the reply questions what this process does; the flow continues`);
6214
+ return false;
6215
+ }
6115
6216
  else if (option === 'irrelevant') {
6116
6217
  // The reply means nothing here: nothing is extracted, so the flow asks again, and no flow moves.
6117
6218
  ranked = 'answers';
@@ -6122,7 +6223,8 @@ async function processActivity(input, userId, engine) {
6122
6223
  return false;
6123
6224
  }
6124
6225
  else if (option === 'abort') {
6125
- // No recovery stamp: the caller chose to stop, so the host has nothing to resume or post-mortem.
6226
+ // No recovery stamp: the caller chose to stop, so the host has nothing to resume or post-mortem. The generic reply
6227
+ // answers, never the global exit (owner 2026-11-11: a model's reading of a withdrawal is not the caller's EXIT).
6126
6228
  abortReply = getSystemMessage(engine, 'cmd_request_aborted');
6127
6229
  terminateForAbort(frame, engine);
6128
6230
  logger.info(`Contextual DISPATCH in '${frame.flowName}': the caller withdrew the request; every flow ended`);
@@ -6161,6 +6263,27 @@ async function processActivity(input, userId, engine) {
6161
6263
  return true;
6162
6264
  }
6163
6265
  };
6266
+ // The global exit (owner 2026-11-11): the whole answer *, EXIT, QUIT or SALIR ends every flow at any question, before any
6267
+ // reader, command or the reply ranker. The global exit's flow answers, else the generic reply. A question that declares a
6268
+ // choice of its own for an exit word (its key or a phrase is *, EXIT, QUIT or SALIR) reads the answer itself.
6269
+ if (getCurrentStackLength(engine) > 0 && isGlobalExit(String(sanitizedInput)) && !declaresExitChoice(getCurrentFlowFrame(engine))) {
6270
+ const exitFrame = getCurrentFlowFrame(engine);
6271
+ exitStart = globalExitStart(engine);
6272
+ terminateForExit(exitFrame, engine);
6273
+ logger.info(`Global exit ${JSON.stringify(sanitizedInput)} in '${exitFrame.flowName}': every flow ended; ${exitStart ? `'${exitStart.flow}' answers` : 'the generic reply answers'}`);
6274
+ if (!exitStart)
6275
+ return getSystemMessage(engine, 'cmd_request_aborted');
6276
+ else { /* fall through: the global exit's flow starts below */ }
6277
+ }
6278
+ else if (getCurrentStackLength(engine) > 0 && (exitStart = textSwitchStart(String(sanitizedInput), getCurrentFlowFrame(engine), engine))) {
6279
+ // keypad 9 (see textSwitchStart): every flow ends and switch-to-text starts below
6280
+ const textFrame = getCurrentFlowFrame(engine);
6281
+ endFlowsFor(textFrame, engine, 'text_requested');
6282
+ logger.info(`Keypad 9 in '${textFrame.flowName}': every flow ended; '${exitStart.flow}' answers`);
6283
+ }
6284
+ else {
6285
+ // not an exit or a text switch, or no flow is active
6286
+ }
6164
6287
  // Check if we're already in a flow (using new stack-of-stacks)
6165
6288
  if (getCurrentStackLength(engine) > 0) {
6166
6289
  logger.info(`\n=== [${new Date().toISOString()}] Flow Handling query: ${input} ===`);
@@ -6238,7 +6361,11 @@ async function processActivity(input, userId, engine) {
6238
6361
  const dispatchedFrom = engine.pendingDispatchFrom;
6239
6362
  engine.pendingDispatchFrom = null;
6240
6363
  try {
6241
- const activatedFlow = activatedThisTurn || (ranked !== null && ranked !== 'new_request') ? null : await isFlowActivated(String(sanitizedInput), engine, userId, preDetected);
6364
+ // The global exit's flow starts as a host start does: no intent detection.
6365
+ if (exitStart)
6366
+ engine.hostStart = exitStart;
6367
+ else { /* intent detection decides, or no activation this turn */ }
6368
+ const activatedFlow = exitStart ? await isFlowActivated(String(sanitizedInput), engine, userId) : activatedThisTurn || (ranked !== null && ranked !== 'new_request') ? null : await isFlowActivated(String(sanitizedInput), engine, userId, preDetected);
6242
6369
  if (activatedFlow)
6243
6370
  activatedThisTurn = true;
6244
6371
  if (dispatchedFrom !== null) {
@@ -7705,7 +7832,7 @@ export class WorkflowEngine {
7705
7832
  }
7706
7833
  // DISPATCH always routes the turn's own input — no value. It may declare the ending of the
7707
7834
  // flows it ends (`outcome` / `reason`, kept only when no flow matches).
7708
- const extra = Object.keys(step).filter(k => !['id', 'type', 'outcome', 'reason', 'recovery', 'onResponse', 'responseContext', 'responseParameters', 'responseVariable', 'responseChoices', 'responseReasonFor', 'responseStay', 'onNoIntent'].includes(k));
7835
+ const extra = Object.keys(step).filter(k => !['id', 'type', 'outcome', 'reason', 'recovery', 'onResponse', 'responseContext', 'responseParameters', 'responseVariable', 'responseChoices', 'responseReasonFor', 'responseConcern', 'responseStay', 'onNoIntent'].includes(k));
7709
7836
  if (extra.length > 0) {
7710
7837
  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", "responseVariable", "responseChoices" and "onNoIntent"`);
7711
7838
  }
@@ -1 +1 @@
1
- export const JSFE_RUNTIME_FINGERPRINT = "sha256:046178eae674f9484c9ef39ac003f3ebbf6bba8eabe8b51a0b088da24c80eed3";
1
+ export const JSFE_RUNTIME_FINGERPRINT = "sha256:63b7c3206cbde58e1ce72c28ba9c38942fd9689d32df488182076bc6ee097b45";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "1.40.2",
3
+ "version": "1.42.0",
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",