jsfe 1.7.6 → 1.7.8

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 (54) hide show
  1. package/dist/forms/choice-flow.js +2 -2
  2. package/dist/forms/continuation-safety.d.ts +4 -0
  3. package/dist/forms/continuation-safety.d.ts.map +1 -0
  4. package/dist/forms/continuation-safety.js +14 -0
  5. package/dist/forms/contracts.d.ts.map +1 -1
  6. package/dist/forms/contracts.js +14 -2
  7. package/dist/forms/flows.d.ts.map +1 -1
  8. package/dist/forms/flows.js +45 -7
  9. package/dist/forms/identity-flows.d.ts.map +1 -1
  10. package/dist/forms/identity-flows.js +10 -3
  11. package/dist/forms/index.d.ts +1 -0
  12. package/dist/forms/index.d.ts.map +1 -1
  13. package/dist/forms/index.js +3 -1
  14. package/dist/helpers/answer.d.ts.map +1 -1
  15. package/dist/helpers/answer.js +10 -2
  16. package/dist/helpers/contextual-response.d.ts +10 -0
  17. package/dist/helpers/contextual-response.d.ts.map +1 -0
  18. package/dist/helpers/contextual-response.js +48 -0
  19. package/dist/helpers/form-conversation.d.ts +22 -0
  20. package/dist/helpers/form-conversation.d.ts.map +1 -1
  21. package/dist/helpers/form-conversation.js +29 -1
  22. package/dist/helpers/form-state.d.ts +3 -2
  23. package/dist/helpers/form-state.d.ts.map +1 -1
  24. package/dist/helpers/form-state.js +93 -8
  25. package/dist/helpers/index.d.ts +15 -1
  26. package/dist/helpers/index.d.ts.map +1 -1
  27. package/dist/helpers/index.js +8 -4
  28. package/dist/helpers/match-inputs.d.ts.map +1 -1
  29. package/dist/helpers/match-inputs.js +7 -2
  30. package/dist/helpers/money.d.ts +4 -0
  31. package/dist/helpers/money.d.ts.map +1 -1
  32. package/dist/helpers/money.js +10 -1
  33. package/dist/helpers/semantic-input-prompt.d.ts +2 -0
  34. package/dist/helpers/semantic-input-prompt.d.ts.map +1 -0
  35. package/dist/helpers/semantic-input-prompt.js +153 -0
  36. package/dist/helpers/semantic-input.d.ts +28 -0
  37. package/dist/helpers/semantic-input.d.ts.map +1 -0
  38. package/dist/helpers/semantic-input.js +47 -0
  39. package/dist/host/capabilities.d.ts.map +1 -1
  40. package/dist/host/capabilities.js +6 -1
  41. package/dist/host/index.d.ts +1 -0
  42. package/dist/host/index.d.ts.map +1 -1
  43. package/dist/host/index.js +1 -0
  44. package/dist/host/registry-composition.d.ts +16 -0
  45. package/dist/host/registry-composition.d.ts.map +1 -0
  46. package/dist/host/registry-composition.js +109 -0
  47. package/dist/index.d.ts +23 -3
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +205 -16
  50. package/dist/runtime-identity.js +1 -1
  51. package/docs/copilot-reference.md +10 -0
  52. package/docs/development-release.md +22 -0
  53. package/docs/forms.md +86 -0
  54. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { closeFormInstance } from './helpers/form-state.js';
2
+ import { validateSemanticInputStep, buildInputAssessment, normalizeInputAssessment } from './helpers/semantic-input.js';
3
+ import { validateContextualResponseStep } from './helpers/contextual-response.js';
1
4
  import { validateFlowRecovery } from './host/flow-recovery.js';
2
5
  import { ACTION_TOOLS } from './forms/action-tools.js';
3
6
  import { claimSessionAction, completeSessionAction } from './forms/session-actions.js';
@@ -2202,6 +2205,7 @@ async function isFlowActivated(input, engine, userId = 'anonymous', detected) {
2202
2205
  flowName: flow.name,
2203
2206
  flowId: flow.id,
2204
2207
  flowVersion: flow.version,
2208
+ safetyRevision: flow.safetyRevision,
2205
2209
  flowStepsStack: cloneFlowValue(flow.steps).reverse(),
2206
2210
  contextStack: [{ role: 'user', content: sanitizeInput(input), timestamp: Date.now() }], // Keep activation input in context for reference
2207
2211
  inputStack: [], // Start empty - only SAY-GET responses go here
@@ -2226,7 +2230,89 @@ function stampStepRecovery(step, currentFlowFrame, engine) {
2226
2230
  engine.stampFlowRecovery(validateFlowRecovery(resolved));
2227
2231
  }
2228
2232
  }
2233
+ /** Intrinsic admission marker for generators and hosts. Absent safetyRevision retains legacy behavior. */
2234
+ export { continuationSafetyProtocol } from './forms/continuation-safety.js';
2235
+ /** Retire obsolete serialized steps, never rebase/restart or feed the old answer into a new action. */
2236
+ function retireUnsafeContinuation(engine, extraStacks = []) {
2237
+ const session = engine.getSessionContext();
2238
+ const frames = [...(engine.flowStacks || []), ...extraStacks].flat().filter(Boolean);
2239
+ const previousRevisions = session.continuationSafetyRevisions || {};
2240
+ const staleForm = Object.values(engine.cargo?.forms || {}).find(state => {
2241
+ const definition = engine.flowsMenu?.find(flow => flow.id === state.definition);
2242
+ const previous = previousRevisions[state.definition], current = definition?.safetyRevision;
2243
+ return (previous !== undefined || current !== undefined) && previous !== current;
2244
+ });
2245
+ const mismatch = frames.find(frame => {
2246
+ const current = engine.flowsMenu?.find(flow => flow.id === frame.flowId);
2247
+ return current?.safetyRevision !== undefined
2248
+ ? current.safetyRevision !== frame.safetyRevision
2249
+ : frame.safetyRevision !== undefined;
2250
+ }) || (staleForm ? { flowId: staleForm.definition, flowName: staleForm.definition } : undefined);
2251
+ const held = session.continuationSafetyHold;
2252
+ if (!mismatch && !held) {
2253
+ session.continuationSafetyRevisions = Object.fromEntries((engine.flowsMenu || []).filter(flow => flow.safetyRevision !== undefined).map(flow => [flow.id, flow.safetyRevision]));
2254
+ return null;
2255
+ }
2256
+ // Retiring tasks must destroy stale accepted confirmations, but keep every unknown effect intact.
2257
+ // No root outcome may hide a descendant's attempted action.
2258
+ const cargo = engine.cargo || {};
2259
+ const forms = cargo.forms || {};
2260
+ const belongs = (state, id) => {
2261
+ const seen = new Set();
2262
+ while (state && !seen.has(state.id)) {
2263
+ if (state.id === id)
2264
+ return true;
2265
+ seen.add(state.id);
2266
+ state = forms[state.parent];
2267
+ }
2268
+ return false;
2269
+ };
2270
+ let unknown = !!engine.cargo?.chargeUnknownAt || Object.keys(engine.cargo?.paymentHolds || {}).length > 0
2271
+ || Object.values(engine.cargo?.actionJournal || {}).some((record) => ['attempted', 'unknown'].includes(record.status));
2272
+ for (const root of Object.values(forms)) {
2273
+ if (root.parent && forms[root.parent])
2274
+ continue;
2275
+ const pending = Object.values(forms).filter(state => belongs(state, root.id))
2276
+ .some(state => Object.values(state.actions || {}).some((record) => ['attempted', 'unknown'].includes(record.status)));
2277
+ if (pending) {
2278
+ unknown = true;
2279
+ for (const state of Object.values(forms).filter(state => belongs(state, root.id))) {
2280
+ state.confirmation = null;
2281
+ state.continuationRetired = true;
2282
+ if (cargo.formTasks?.[state.definition] === state.id)
2283
+ delete cargo.formTasks[state.definition];
2284
+ if (cargo.formConfirm)
2285
+ delete cargo.formConfirm[state.id];
2286
+ for (const proposal of Object.values(state.inputProposals || {}))
2287
+ delete proposal.approval;
2288
+ delete state.proposalPrompt;
2289
+ }
2290
+ continue;
2291
+ }
2292
+ closeFormInstance(engine.cargo, root.id, false);
2293
+ }
2294
+ if (unknown || held)
2295
+ session.continuationSafetyHold = held || { reason: 'obsolete_continuation_action_unknown', flowId: mismatch?.flowId };
2296
+ engine.hostStart = null;
2297
+ engine.pendingDispatchFrom = null;
2298
+ delete session.lastTurnDispatch;
2299
+ delete session.lastFlowRecovery;
2300
+ engine.resetFlowState(); // cargo, journals, payment holds and unknown FORM records are deliberately preserved.
2301
+ engine.stampFlowOutcome({ flowName: mismatch?.flowName || held?.flowId || '', outcome: 'unresolved', reason: unknown || held ? 'obsolete_continuation_action_unknown' : 'obsolete_continuation', endedBy: 'completion' });
2302
+ const es = engine.getSessionLanguage() === 'es';
2303
+ const message = es
2304
+ ? 'La solicitud anterior cambió y no puedo continuarla de forma segura. No he repetido ninguna acción ni he procesado su último mensaje.'
2305
+ : 'The earlier request changed and I cannot safely continue it. I have not repeated any action or processed your latest message.';
2306
+ if (!unknown && !held)
2307
+ return message + (es ? ' Por favor, vuelva a indicar su solicitud.' : ' Please state your request again.');
2308
+ const contact = engine.cargo?.contact_info;
2309
+ return message + (es ? ' Comuníquese con atención al cliente fuera de esta conversación para revisar la acción pendiente.' : ' Please contact customer support outside this conversation to review the pending action.')
2310
+ + (typeof contact === 'string' && contact.trim() ? ' ' + contact.trim() : '');
2311
+ }
2229
2312
  async function playFlowFrame(engine) {
2313
+ const retired = retireUnsafeContinuation(engine);
2314
+ if (retired)
2315
+ return retired;
2230
2316
  // Enhanced recursion protection using natural stack depth
2231
2317
  const stackDepth = getCurrentStackLength(engine);
2232
2318
  if (stackDepth > 20) {
@@ -2489,6 +2575,8 @@ async function playStep(currentFlowFrame, engine) {
2489
2575
  return await handleSubFlowStep(currentFlowFrame, engine);
2490
2576
  case 'SET':
2491
2577
  return handleSetStep(currentFlowFrame, engine);
2578
+ case 'ASSESS-INPUT':
2579
+ return await handleAssessInputStep(currentFlowFrame, engine);
2492
2580
  case 'SWITCH':
2493
2581
  return await handleSwitchStep(currentFlowFrame, engine);
2494
2582
  case 'CASE':
@@ -2794,7 +2882,7 @@ function enforceParameterTypes(flow, parameters) {
2794
2882
  return result;
2795
2883
  }
2796
2884
  /** The structured form of the intent-detection call, passed to aiCallback as its 4th argument. */
2797
- function buildDetectFlowRequest(input, lastChatTurn, flows) {
2885
+ function buildDetectFlowRequest(input, lastChatTurn, flows, responseContext) {
2798
2886
  const conversation = [];
2799
2887
  for (const entry of [lastChatTurn?.user, lastChatTurn?.assistant]) {
2800
2888
  if (entry && (entry.role === 'user' || entry.role === 'assistant')) {
@@ -2804,6 +2892,8 @@ function buildDetectFlowRequest(input, lastChatTurn, flows) {
2804
2892
  // absent, or a role the conversation cannot carry
2805
2893
  }
2806
2894
  }
2895
+ if (responseContext !== undefined)
2896
+ conversation.push({ role: 'assistant', content: responseContext });
2807
2897
  return {
2808
2898
  task: 'detect_flow',
2809
2899
  input: String(sanitizeInput(input)),
@@ -2829,8 +2919,8 @@ function buildDetectFlowRequest(input, lastChatTurn, flows) {
2829
2919
  * ({ flowName } / { parameters }). A stage-1 failure reaches the host as before; a stage-2 failure starts the flow
2830
2920
  * without its parameters (it asks for them) rather than losing the turn.
2831
2921
  */
2832
- async function detectFlowInTwoStages(input, engine, flows) {
2833
- const { input: cleanInput, conversation } = buildDetectFlowRequest(input, engine.lastChatTurn, []);
2922
+ async function detectFlowInTwoStages(input, engine, flows, responseContext) {
2923
+ const { input: cleanInput, conversation } = buildDetectFlowRequest(input, engine.lastChatTurn, [], responseContext);
2834
2924
  const stage1 = buildFlowStage(cleanInput, conversation, flows.map(f => ({ id: f.id, name: f.name, description: String(f.description ?? '') })));
2835
2925
  const reply1 = parseStageReply(await fetchAiResponse(stage1.llm.system, stage1.llm.user, engine.aiCallback, engine.aiTimeOut, stageSchema('detect_flow', stage1.llm.schema), stage1));
2836
2926
  const said = String(reply1.flowName ?? 'None');
@@ -2854,6 +2944,8 @@ async function detectFlowInTwoStages(input, engine, flows) {
2854
2944
  return { flow, parameters: enforceParameterEnums(flow, enforceParameterTypes(flow, ownParametersOnly(flow, given))) };
2855
2945
  }
2856
2946
  catch (error) {
2947
+ if (flow.id === '__jsfe_continue_current__' && responseContext !== undefined)
2948
+ throw error;
2857
2949
  logger.warn(`detectFlowWithParameters: stage 2 failed for "${flow.name}" (${error.message}) - the flow starts without its parameters`);
2858
2950
  return { flow, parameters: {} };
2859
2951
  }
@@ -2874,7 +2966,7 @@ export async function getFlowForInput(input, engine) {
2874
2966
  const result = await detectFlowWithParameters(input, engine);
2875
2967
  return result ? result.flow : null;
2876
2968
  }
2877
- export async function detectFlowWithParameters(input, engine, continuation) {
2969
+ export async function detectFlowWithParameters(input, engine, continuation, responseContext) {
2878
2970
  // CRITICAL: This function requires AI access via engine.aiCallback
2879
2971
  // Without AI, the engine cannot detect user intent and activate flows
2880
2972
  // Sessions would never be activated as no workflows could be triggered
@@ -2922,7 +3014,7 @@ export async function detectFlowWithParameters(input, engine, continuation) {
2922
3014
  return null;
2923
3015
  }
2924
3016
  if (engine.intentDetection === 'two-stage') {
2925
- return await detectFlowInTwoStages(input, engine, flowsForIntentDetection);
3017
+ return await detectFlowInTwoStages(input, engine, flowsForIntentDetection, responseContext);
2926
3018
  }
2927
3019
  else {
2928
3020
  // the original single call, below
@@ -2954,7 +3046,9 @@ export async function detectFlowWithParameters(input, engine, continuation) {
2954
3046
  </chat-history>\n\n`;
2955
3047
  }
2956
3048
  // Let AI errors (timeout, communication failures) propagate to the host
2957
- const request = buildDetectFlowRequest(input, engine.lastChatTurn, flowsForIntentDetection);
3049
+ if (responseContext !== undefined)
3050
+ context += `<current-response-context>\n${responseContext}\n</current-response-context>\n`;
3051
+ const request = buildDetectFlowRequest(input, engine.lastChatTurn, flowsForIntentDetection, responseContext);
2958
3052
  const aiResponse = await fetchAiTask(task, rules, context, input, flowsForIntentDetection, jsonSchema, engine.aiCallback, engine.aiTimeOut, request);
2959
3053
  if (aiResponse && aiResponse.flowName && aiResponse.flowName !== 'None' && aiResponse.flowName !== 'null') {
2960
3054
  const flow = flowsMenu.concat(continuation ? [continuation] : []).find(flow => flow.name.toLowerCase() === aiResponse.flowName.toLowerCase() || flow.id === aiResponse.flowName);
@@ -3456,6 +3550,7 @@ async function handleToolStep(currentFlowFrame, engine) {
3456
3550
  flowName: rebootFlow.name,
3457
3551
  flowId: rebootFlow.id,
3458
3552
  flowVersion: rebootFlow.version,
3553
+ safetyRevision: rebootFlow.safetyRevision,
3459
3554
  flowStepsStack: cloneFlowValue(rebootFlow.steps).reverse(),
3460
3555
  contextStack: [{ role: 'user', content: input, timestamp: Date.now() }],
3461
3556
  inputStack: [input],
@@ -3513,6 +3608,7 @@ async function handleToolStep(currentFlowFrame, engine) {
3513
3608
  flowName: onFailFlow.name,
3514
3609
  flowId: onFailFlow.id,
3515
3610
  flowVersion: onFailFlow.version,
3611
+ safetyRevision: onFailFlow.safetyRevision,
3516
3612
  flowStepsStack: cloneFlowValue(onFailFlow.steps).reverse(),
3517
3613
  contextStack: [...currentFlowFrame.contextStack], // Inherit context
3518
3614
  inputStack: [...currentFlowFrame.inputStack],
@@ -3812,6 +3908,43 @@ function addFlowContextGuidance(message, flowFrame, engine) {
3812
3908
  return message + defaultSeparator + guidance;
3813
3909
  }
3814
3910
  }
3911
+ /** An explicitly declared field meaning is assessed separately from intent detection.
3912
+ * Clear the output before awaiting: a timeout or malformed verdict cannot retain an old acceptance.
3913
+ * The callback receives only this field's declared context; no account facts or unrelated history.
3914
+ */
3915
+ async function handleAssessInputStep(frame, engine) {
3916
+ const step = frame.flowStepsStack.pop();
3917
+ const definition = engine.flowsMenu.find(flow => flow.id === frame.flowId || flow.name === frame.flowName);
3918
+ validateSemanticInputStep(step, definition);
3919
+ const variable = step.variable;
3920
+ frame.variables[variable] = { ok: false, disposition: 'retry', unavailable: true };
3921
+ const resolve = (text) => interpolateMessage(String(text ?? ''), frame.contextStack, frame.variables, engine);
3922
+ const input = resolve(step.value);
3923
+ const question = resolve(step.question);
3924
+ const purpose = resolve(step.purpose);
3925
+ const acceptance = resolve(step.acceptance);
3926
+ if (!input.trim()) {
3927
+ frame.variables[variable] = { ok: false, disposition: 'retry' };
3928
+ return 'Input assessment received an empty candidate';
3929
+ }
3930
+ if (!question.trim() || !purpose.trim() || !acceptance.trim()) {
3931
+ logger.warn(`ASSESS-INPUT step ${step.id || ''} could not validate its field; the input remains unaccepted`);
3932
+ return 'Input assessment requires a complete field context';
3933
+ }
3934
+ try {
3935
+ const assessment = buildInputAssessment({ value: input, question, purpose, acceptance });
3936
+ const schema = assessment.schema;
3937
+ const response = await fetchAiResponse(assessment.system, assessment.user, engine.aiCallback, engine.aiTimeOut, schema, { task: 'assess_input', input, question, purpose, acceptance });
3938
+ const result = normalizeInputAssessment(response);
3939
+ frame.variables[variable] = result;
3940
+ if ('unavailable' in result && result.unavailable === true)
3941
+ logger.warn(`ASSESS-INPUT step ${step.id || ''} could not validate its field; the input remains unaccepted`);
3942
+ }
3943
+ catch {
3944
+ logger.warn(`ASSESS-INPUT step ${step.id || ''} could not validate its field; the input remains unaccepted`);
3945
+ }
3946
+ return 'Input assessment completed';
3947
+ }
3815
3948
  function handleSetStep(currentFlowFrame, engine) {
3816
3949
  // Extract what we need from the currentFlowFrame
3817
3950
  const step = currentFlowFrame.flowStepsStack.pop(); // This handler pops its own step
@@ -4157,6 +4290,7 @@ async function handleSubFlowStep(currentFlowFrame, engine) {
4157
4290
  flowName: subFlow.name,
4158
4291
  flowId: subFlow.id,
4159
4292
  flowVersion: subFlow.version,
4293
+ safetyRevision: subFlow.safetyRevision,
4160
4294
  flowStepsStack: cloneFlowValue(subFlow.steps).reverse(),
4161
4295
  contextStack: [{ role: 'user', content: input, timestamp: Date.now() }],
4162
4296
  inputStack: [input],
@@ -4177,6 +4311,7 @@ async function handleSubFlowStep(currentFlowFrame, engine) {
4177
4311
  currentFlowFrame.flowName = subFlow.name;
4178
4312
  currentFlowFrame.flowId = subFlow.id;
4179
4313
  currentFlowFrame.flowVersion = subFlow.version;
4314
+ currentFlowFrame.safetyRevision = subFlow.safetyRevision;
4180
4315
  currentFlowFrame.flowStepsStack = cloneFlowValue(subFlow.steps).reverse();
4181
4316
  addToContextStack(currentFlowFrame.contextStack, 'user', input);
4182
4317
  currentFlowFrame.inputStack.push(input);
@@ -4216,6 +4351,7 @@ async function handleSubFlowStep(currentFlowFrame, engine) {
4216
4351
  flowName: subFlow.name,
4217
4352
  flowId: subFlow.id,
4218
4353
  flowVersion: subFlow.version,
4354
+ safetyRevision: subFlow.safetyRevision,
4219
4355
  flowStepsStack: cloneFlowValue(subFlow.steps).reverse(),
4220
4356
  contextStack: [{ role: 'user', content: input, timestamp: Date.now() }],
4221
4357
  inputStack: [input],
@@ -5701,6 +5837,7 @@ async function handlePendingInterruptionSwitch(engine, userId) {
5701
5837
  flowName: targetFlow,
5702
5838
  flowId: targetFlowDefinition.id,
5703
5839
  flowVersion: targetFlowDefinition.version || '1.0',
5840
+ safetyRevision: targetFlowDefinition.safetyRevision,
5704
5841
  flowStepsStack: cloneFlowValue(targetFlowDefinition.steps).reverse(),
5705
5842
  contextStack: [],
5706
5843
  inputStack: [],
@@ -5766,6 +5903,7 @@ async function handleRegularFlowInterruption(intentAnalysis, engine, userId) {
5766
5903
  flowName: targetFlow,
5767
5904
  flowId: targetFlowDefinition.id,
5768
5905
  flowVersion: targetFlowDefinition.version || '1.0',
5906
+ safetyRevision: targetFlowDefinition.safetyRevision,
5769
5907
  flowStepsStack: cloneFlowValue(targetFlowDefinition.steps).reverse(),
5770
5908
  contextStack: [], // Start with empty context - don't use interruption input
5771
5909
  inputStack: [], // Start with empty input stack - new flow will get proper input next
@@ -5838,29 +5976,48 @@ async function processActivity(input, userId, engine) {
5838
5976
  // One routing decision for the original turn, shared by guarded and ordinary dispatch.
5839
5977
  let detected;
5840
5978
  let activatedThisTurn = false;
5979
+ let detectedResponseContext;
5841
5980
  let guardedRoutingFailed = false;
5842
- const route = async (continuation) => {
5843
- if (detected === undefined)
5844
- detected = await detectFlowWithParameters(String(sanitizedInput), engine, continuation);
5981
+ const route = async (continuation, responseContext) => {
5982
+ if (detected === undefined) {
5983
+ detected = await detectFlowWithParameters(String(sanitizedInput), engine, continuation, responseContext);
5984
+ detectedResponseContext = responseContext;
5985
+ }
5986
+ else if (continuation?.parameters?.length && (responseContext !== detectedResponseContext || JSON.stringify(continuation.parameters) !== JSON.stringify(detected?.flow.parameters))) {
5987
+ throw new Error('A typed contextual response cannot reuse an incompatible routing decision this turn');
5988
+ }
5845
5989
  return detected;
5846
5990
  };
5847
5991
  engine.dispatchIfMatched = async (frame, step) => {
5848
- if (activatedThisTurn)
5992
+ if (activatedThisTurn && step.responseParameters === undefined && step.responseVariable === undefined)
5849
5993
  return false;
5850
5994
  if (engine.flowsMenu.some(flow => flow.name.toLowerCase() === 'continuecurrent' || flow.id.toLowerCase() === '__jsfe_continue_current__'))
5851
5995
  throw new Error('ContinueCurrent is reserved for contextual dispatch');
5996
+ let declaration;
5997
+ try {
5998
+ declaration = validateContextualResponseStep(step, engine.flowsMenu.find(flow => flow.id === frame.flowId));
5999
+ if (activatedThisTurn && declaration)
6000
+ throw new Error('Typed contextual response cannot classify after a flow activation this turn');
6001
+ }
6002
+ catch (error) {
6003
+ guardedRoutingFailed = true;
6004
+ throw error;
6005
+ }
5852
6006
  const context = interpolateMessage(step.responseContext, frame.contextStack, frame.variables, engine).trim();
5853
- const continuation = { id: '__jsfe_continue_current__', name: 'ContinueCurrent', version: '1.0.0', primary: true, steps: [], 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.` };
6007
+ 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.` };
5854
6008
  let selected;
5855
6009
  try {
5856
- selected = await route(continuation);
6010
+ selected = await route(continuation, context);
5857
6011
  }
5858
6012
  catch (error) {
5859
6013
  guardedRoutingFailed = true;
5860
6014
  throw error;
5861
6015
  }
5862
- if (selected?.flow.id === continuation.id)
6016
+ if (selected?.flow.id === continuation.id) {
6017
+ if (declaration)
6018
+ frame.variables[declaration.variable] = structuredClone(selected.parameters || {});
5863
6019
  return false;
6020
+ }
5864
6021
  stampStepRecovery(step, frame, engine);
5865
6022
  terminateForDispatch(frame, engine);
5866
6023
  if (!selected)
@@ -6252,6 +6409,10 @@ export class WorkflowEngine {
6252
6409
  hostLogger = hostLogger || logger; // Fallback to global fake logger if none provided
6253
6410
  logger = withPiiRedaction(hostLogger); // Assign to global logger (a SAY-GET's `pii` answer never reaches it)
6254
6411
  this.aiCallback = aiCallback;
6412
+ for (const flow of flowsMenu) {
6413
+ if (flow.safetyRevision !== undefined && (typeof flow.safetyRevision !== 'string' || !flow.safetyRevision.trim() || flow.safetyRevision !== flow.safetyRevision.trim()))
6414
+ throw new Error('Invalid safetyRevision for flow ' + flow.id);
6415
+ }
6255
6416
  this.flowsMenu = applyWraps(flowsMenu);
6256
6417
  if (toolsRegistry.some(tool => ACTION_TOOLS.some(internal => internal.id === tool.id)))
6257
6418
  throw new Error('Internal JSFE action tool identities are reserved');
@@ -6318,6 +6479,7 @@ export class WorkflowEngine {
6318
6479
  userId: userId,
6319
6480
  createdAt: new Date(),
6320
6481
  lastActivity: new Date(),
6482
+ continuationSafetyRevisions: Object.fromEntries((this.flowsMenu || []).filter(flow => flow.safetyRevision !== undefined).map(flow => [flow.id, flow.safetyRevision])),
6321
6483
  flowStacks: [[]], // Initialize as array with one empty stack (pure data)
6322
6484
  globalAccumulatedMessages: [],
6323
6485
  lastChatTurn: {},
@@ -6414,6 +6576,11 @@ export class WorkflowEngine {
6414
6576
  if (engineSessionContext) {
6415
6577
  engineSessionContext.lastActivity = this.lastActivity;
6416
6578
  }
6579
+ // A durable checkpoint cannot release an already established obsolete-action safety hold.
6580
+ if (contextEntry.role === 'user' && engineSessionContext.continuationSafetyHold) {
6581
+ engineSessionContext.response = retireUnsafeContinuation(this);
6582
+ return engineSessionContext;
6583
+ }
6417
6584
  // Recover durable effects before the new message can mutate an older saved session.
6418
6585
  // A successfully saved session carries its observed sequence even when acknowledgement failed.
6419
6586
  delete engineSessionContext.lastTurnRecovery;
@@ -6460,6 +6627,13 @@ export class WorkflowEngine {
6460
6627
  recoveredAction = true;
6461
6628
  }
6462
6629
  }
6630
+ if (contextEntry.role === 'user') {
6631
+ const retired = retireUnsafeContinuation(this, suspendedRecoveryStacks || []);
6632
+ if (retired) {
6633
+ engineSessionContext.response = retired;
6634
+ return engineSessionContext;
6635
+ }
6636
+ }
6463
6637
  // Role-based processing logic
6464
6638
  if (contextEntry.role === 'user') {
6465
6639
  // A sensitive answer (SAY-GET `pii`) is kept out of every log line of this turn, raw and as its digits
@@ -6790,6 +6964,7 @@ export class WorkflowEngine {
6790
6964
  }
6791
6965
  // Stamp the one-shot host-facing outcome for a flow that terminated this turn
6792
6966
  // (sessionContext is private; finalizeFlowTransaction goes through this).
6967
+ getSessionContext() { return this.sessionContext; }
6793
6968
  stampFlowRecovery(recovery) {
6794
6969
  const value = validateFlowRecovery(recovery);
6795
6970
  if (value.form && this.cargo?.forms?.[value.form]?.definition !== value.flow)
@@ -7197,7 +7372,7 @@ export class WorkflowEngine {
7197
7372
  return;
7198
7373
  }
7199
7374
  // Validate step type
7200
- const validStepTypes = ['SAY', 'SAY-GET', 'SET', 'SWITCH', 'CASE', 'CALL-TOOL', 'FLOW', 'RETURN', 'END', 'DISPATCH'];
7375
+ const validStepTypes = ['SAY', 'SAY-GET', 'SET', 'SWITCH', 'CASE', 'CALL-TOOL', 'FLOW', 'RETURN', 'END', 'DISPATCH', 'ASSESS-INPUT'];
7201
7376
  if (!validStepTypes.includes(step.type)) {
7202
7377
  state.errors.push(`Step "${step.id}" in flow "${flowDef.name}" has invalid type: ${step.type}`);
7203
7378
  return;
@@ -7213,6 +7388,14 @@ export class WorkflowEngine {
7213
7388
  case 'SET':
7214
7389
  this._validateSetStep(step, flowDef, state, opts, currentScope);
7215
7390
  break;
7391
+ case 'ASSESS-INPUT':
7392
+ try {
7393
+ validateSemanticInputStep(step, flowDef);
7394
+ }
7395
+ catch (error) {
7396
+ state.errors.push(`ASSESS-INPUT step "${step.id}" in flow "${flowDef.name}": ${error.message}`);
7397
+ }
7398
+ break;
7216
7399
  case 'SWITCH':
7217
7400
  this._validateSwitchStep(step, flowDef, state, opts, currentScope);
7218
7401
  break;
@@ -7226,11 +7409,17 @@ export class WorkflowEngine {
7226
7409
  this._validateSubFlowStep(step, flowDef, state, opts, currentScope);
7227
7410
  break;
7228
7411
  case 'DISPATCH': {
7412
+ try {
7413
+ validateContextualResponseStep(step, flowDef);
7414
+ }
7415
+ catch (error) {
7416
+ state.errors.push(`DISPATCH step \"${step.id}\" in flow \"${flowDef.name}\": ${error.message}`);
7417
+ }
7229
7418
  // DISPATCH always routes the turn's own input — no value. It may declare the ending of the
7230
7419
  // flows it ends (`outcome` / `reason`, kept only when no flow matches).
7231
- const extra = Object.keys(step).filter(k => !['id', 'type', 'outcome', 'reason', 'recovery', 'onResponse', 'responseContext'].includes(k));
7420
+ const extra = Object.keys(step).filter(k => !['id', 'type', 'outcome', 'reason', 'recovery', 'onResponse', 'responseContext', 'responseParameters', 'responseVariable'].includes(k));
7232
7421
  if (extra.length > 0) {
7233
- 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" and "responseContext"`);
7422
+ 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"`);
7234
7423
  }
7235
7424
  else if (step.onResponse !== undefined && step.onResponse !== 'continue') {
7236
7425
  state.errors.push(`DISPATCH step "${step.id}" in flow "${flowDef.name}" onResponse must be "continue" when provided`);
@@ -1 +1 @@
1
- export const JSFE_RUNTIME_FINGERPRINT = "sha256:e1f92f33ed78b9489b674bdfe64d7aa56c2ea039cee48410767bbf6e0f22bfbc";
1
+ export const JSFE_RUNTIME_FINGERPRINT = "sha256:695c0b98dba39e516506f44622e8e96e73a3a870e85dd47398cd00962782bf6d";
@@ -51,6 +51,11 @@ DISPATCH — Ends every flow (all stacks, and any SAY output not yet delivered)
51
51
 
52
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
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
+
54
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.
55
60
 
56
61
  ## Cargo — Session-Persistent State
@@ -88,3 +93,8 @@ Multiple assignments MUST use comma operator, NEVER semicolons (semicolons termi
88
93
  1. SAY in an onFail handler — An onFail with a SAY step will display the error message but then continue to the next step, typically leading to unintended behavior. Use FLOW with reboot to a handler, or RETURN.
89
94
  2. SAY in a CASE/SWITCH branch — A branch whose only step is SAY will continue execution into the following step. If the flow should terminate at that point, follow it with END (back to the caller) or use RETURN (with a language-aware expression), or FLOW with reboot.
90
95
  3. Referencing non-existent flows — Every FLOW step value must be a flow ID that exists. Return an array of flows if new sub-flows are needed.
96
+
97
+
98
+ ### Optional field assessment (unreleased)
99
+
100
+ An `ASSESS-INPUT` step validates a field separately from intent routing. Declare an object `variable`, and string templates `value`, `question`, `purpose`, and `acceptance`. The callback receives `task: "assess_input"` and a strict schema for `{ok, disposition}`. Only `{ok: true, disposition: "accept"}` accepts a value; the engine never rewrites the supplied text. Missing callbacks, unavailable models, timeouts, invalid JSON and contradictory verdicts return an unaccepted retry. FORM input `meaning` declarations invoke this generic step; ordinary inputs do not invoke it. See forms.md for the declaration and cancellation/recovery rules.
@@ -53,3 +53,25 @@ Contextual DISPATCH is opt-in through `onResponse:"continue"` and `responseConte
53
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
54
 
55
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.
66
+
67
+ ## 1.7.8 explicit intake meaning and continuation safety
68
+
69
+ Optional declared field meanings use ASSESS-INPUT with a strict accept/retry/cancel/redirect result. This validation never grants action consent. Technical failure leaves input unaccepted and asks for a technical retry; late answers do not commit withdrawn work. Existing unmarked inputs do not invoke an assessment. The matched host qualifies GPT-6 Sol for this task, requires its schema-capable transport, and does not fall back to an unqualified model.
70
+
71
+ Proposal dependency handling preserves a corrected candidate through its new explicit confirmation. Opted-in continuation safety revisions stop obsolete frames and yielded form continuations before consuming new input. An uncertain prior effect remains held for authoritative reconciliation; no automatic replay or expiry releases it. Session-only mode and its confirmation, subject and attempted/completed/unknown guards remain explicit. Storage encoding and durability defaults do not change.
72
+
73
+ Payment interpretation rejects partial cents and card references as replacement amounts, distinguishes historical payment reports from new instructions, and keeps balance distinct from amount due. Identity recovery has bounded resend, lost-phone and disambiguation paths. Saved-card profiles deduplicate by stable identity and omit declined profiles.
74
+
75
+ Reviewed acceptance: 89 SDK test files; 142 legacy and 142 native flow suites; 626 hermetic and 626 real-model primary executions across 17 primaries and 167 applicable paths. Targeted model probes: consent/intake 229/230, payments 16/16 per flow set, routing 132/132. The one consent deadline safely left input unaccepted with no case filed; its late verdict was retry, and bounded same-source rechecks passed in both flow sets. Original observations remain retained. Customer effects use local stubs; these results do not claim a literal replay of the October 21 production day.
76
+
77
+ Owner authorized publication, exact pins in both consumers, dev host deployment and matching shared/ai-ar-ql activation in all three dev configs with session-only actions. Production deployment and activation are excluded. Shopify Policy remains unchanged with its later review recorded as a tenant TODO. Match runtime, host and regenerated definitions before activation; existing uncertain work must retain its hold.
package/docs/forms.md CHANGED
@@ -183,3 +183,89 @@ Provider menus keep terminal phrases distinct from neutral menu answers. If an a
183
183
  ### Identification handoff on an unmapped answer
184
184
 
185
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.
228
+
229
+ ### Optional semantic field validation
230
+
231
+ A field may declare `meaning: { purpose, acceptance }` when a shape reader alone cannot establish that an answer supplies the requested information. Both values are nonempty strings. For example:
232
+
233
+ ```js
234
+ {
235
+ name: 'issue_details',
236
+ profile: { kind: 'text', narrative: true },
237
+ meaning: {
238
+ purpose: 'Collect the specific issue for the service team.',
239
+ acceptance: 'Concrete details of what happened or the requested resolution; a fragment or a generic announcement of a complaint is insufficient.'
240
+ },
241
+ question: 'What happened?'
242
+ }
243
+ ```
244
+
245
+ The common validation batch uses the prepared owning field's question and criteria to run `ASSESS-INPUT` independently of intent detection. It checks conversational readings and untrusted activation seeds through the same path; several fields can be assessed in one turn. Already accepted, unchanged fields do not need another assessment. Fields without `meaning` retain their existing behavior and make no assessment call.
246
+
247
+ The model returns exactly `{ ok: boolean, disposition: 'accept' | 'retry' | 'cancel' | 'redirect' }`. Only `ok: true` paired with `accept` permits ordinary field validation and commitment. The original candidate remains unchanged. A timeout, missing callback, malformed response or inconsistent verdict leaves it unaccepted and adds an engine-owned `unavailable: true` flag. The model cannot supply that flag through its exact two-field response schema. Technical unavailability gets distinct retry wording; semantic rejection asks for the requested data. Both consume the same bounded interaction budget, so outages cannot create infinite retries. `retry` uses the existing bounded field retry policy; `redirect` yields with the owning task available for recovery. An explicit `cancel` retires that task, except that an unknown action result remains held for reconciliation.
248
+
249
+ Semantic completeness is separate from consent: it must never substitute for an exact confirmation or authorize a charge, cancellation, send or case submission. Criteria should describe the particular field: an account identifier, requested increase amount, payment date and issue narrative have different acceptance requirements. Short but concrete answers can be valid; no word-count rule determines completeness.
250
+
251
+ Legacy callers can use the shared `collect-semantic-answer` worker with `question`, `question_es`, `purpose`, `acceptance`, optional `choices` and `digits`, and `context` / `context_es`. It returns `cargo.semanticAnswer`, `cargo.choice` and `cargo.choiceText`; the same FORM owns retries, validation and recovery.
252
+
253
+ Flows opting in declare `jsfe:semantic-input-validation:v1` and receive a runtime guard. The underlying explicit `ASSESS-INPUT` step takes template strings `value`, `question`, `purpose`, `acceptance` and a `variable` naming a declared object result. The callback request has `task: 'assess_input'`; it is a data-validation request, separate from `detect_flow`.
254
+
255
+ When a declared dependency (including an ancestor subform dependency) has a pending input proposal, dependent candidates wait for that proposal rather than using the previous committed context. Deferred candidates retain the exact proposal identity. Confirming the controller preserves those candidates through dependency invalidation and validates them under the new context; declining or superseding it discards them. Independent fields still collect normally. Declare `depends_on` for contextual prerequisites and `reset_on` for changes that invalidate previously collected data.
256
+
257
+ ### Safety revisions for saved continuations
258
+
259
+ `withSafetyRevision(flow, token)` opts a definition into the `jsfe:continuation-safety:v1` contract. The token is a nonempty string, independent of the informational flow version. Change it when old serialized steps or retained FORM schemas must no longer execute. The helper adds an executable protocol guard and augments an existing contract's requirements; it does not invent a FORM contract for legacy workers. Hosts register the current `STANDARD_FUNCTIONS`.
260
+
261
+ New frames save the token. Sessions also save the definition-token snapshot so yielded FORM tasks with no active frames are checked. Before new input is processed, and after durable checkpoint restoration, a missing or different token retires obsolete stacks and safely closes unexecuted FORM tasks. The engine does not rebase old steps, restart a request, forward the old answer, or repeat effects. It returns a localized explanation and `unresolved / obsolete_continuation`; a subsequent fresh request must collect new confirmation. Unopted definitions retain their previous behavior.
262
+
263
+ If retirement encounters any attempted/unknown FORM action, session journal record, or existing payment uncertainty hold, it preserves the effect evidence and quarantines the old task. Its confirmation/proposal approvals and task index are invalidated. The session receives `continuationSafetyHold`; later turns cannot execute flows or consume durable checkpoints. This conservative restriction applies only to obsolete continuations with uncertain effects, and directs the user to configured support outside that conversation. There is no automatic release, timeout or retry. External reconciliation must resolve the effect and retire the quarantined task before deliberately clearing the hold. Cargo, identity data, action ledgers and payment holds are preserved.
264
+
265
+ The runtime never treats the informational `version` as a hot-reload instruction. An older runtime without the intrinsic contract must not activate revised definitions: matched capability admission rejects unsupported intrinsic requirements, and the executable protocol guard fails closed in standalone engines.
266
+
267
+ Semantic dispositions describe the caller's intent, not permission to perform an action. An explicit replacement request yields with `redirect`; withdrawing the owning request or prohibiting its intended action yields `cancel`. Refusing one field while continuing the same request yields `retry`, unless the declaration permits that answer (such as an unknown date). Factual negative allegations remain eligible data. Candidate instructions are evidence for this classification; they cannot change the evaluator's rules or authorize backend cancellation.
268
+
269
+ A field meaning must explicitly identify both the field and its owning service/action in `purpose`, for example collecting a date before filing a caller-requested investigation. A vague instruction to collect information does not identify what a withdrawal applies to. Author this context in the declaration; never derive it from caller keywords or rewrite it at runtime.
270
+
271
+ Callbacks serving `assess_input` (schema `input_assessment`) require semantic model qualification against acceptance, withdrawal, field-only refusal, permitted unknowns, factual denials, and task corrections. Valid JSON alone is insufficient: a model can return a schema-valid unsafe acceptance. The engine remains provider-agnostic and rejects unavailable/malformed responses; the host must select a qualified model and must not silently race or fall back to an unqualified general or intent model. Requalify proposed alternatives with the same synthetic contrasts and actual engine paths before enabling them.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsfe",
3
- "version": "1.7.6",
3
+ "version": "1.7.8",
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",